I have the following domain models:
public class User
{
public int Id { get; set; }
public ICollection<Product> Products { get; set; }
}
public class Product
{
public int Id { get; set; }
public decimal Price { get; set; }
}
My User entity has a collection of Products, and no Product can be created without an User.
I am using EntityFramework Code First approach, which requires me to declare the Foreign Key on my Product entity, thus changing it to:
public class Product
{
public int Id { get; set; }
public decimal Price { get; set; }
public int UserId { get; set; }
}
I dont quite like this because, from the domain point of view, it is not interesting to have the User foreign key shown in my Product entity. This, however, does not bring any harm to me and I can live with it. Please, mind that I am using an ORM to simplify my work, so I am okay with it to an extent.
Is it okay to my domain entities having properties or such things only to satisfy my ORM of choice requirements?
3
I’ve heard Vaugn Vernon say about EF that you shouldn’t spend time battling EF in order to make it look like a domain model because EF is much more inflexible than other ORMs. So his advise if you want to use EF is to just have a state object behind the scenes which fits EF and then just let your domain model use that for data storage.
2
If you use the fluent mapping API doing:
HasMany(x => x.Products);
Should be sufficient to create the foreign key relationship between User and Product without needed the UserId property to be specified on Product.
Also note that EF can map data to private properties(and use private ctors and setters) so if a detail like that was absolutely unavoidable you should be able avoid exposing that on your domain.
As a side-note (it may just be your example code); if you want to lazy load Products you will need to specify it as virtual or specify it as an include when performing your queries.