For each entity that has a one to many relation with other entity when i trying to add a new item it seems like i have to define these list of items that relates to this entity.
For example, lets say that i have a ProductType entity that has a list of Products as following:
[Table]
public class ProductType
{
[Column(IsPrimaryKey = true, IsDbGenerated = true)]
public int Id { get; private set; }
[Column]
public string Name { get; set; }
private EntitySet<Product> _products;
[Association(Storage = "_products", ThisKey = "Id", OtherKey = "ProductTypeId")]
public EntitySet<Product> Products
{
get { return _products; }
set { _products.Assign(value); }
}
}
when i try to add a new ProductType like that:
ProductType newType = new ProductType { Name = "newType" };
_productRepository.Add(newType); //InsertOnSubmit() and SaveChanges()
it gives me an exception that Products is null:
Object reference not set to an instance of an object
the same problem with all the entities that has a one to many relation with other entities. so how can i allow null for the EntitySet<> that represents a one to many Relation
You’re missing the generated constructor setting the default for the Products entity set. Compare this against what the designer generates for you. For example, the Product constructor for Northwind looks like this: