I am working on Entity Framework 4.1 and using data annotations for foreign keys. I want to know how can we define one to many relationship between product and categories. I want to map category. categoryId with product.cid
public class Category { public string CategoryId { get; set; } public string Name { get; set; } public virtual ICollection<Product> Products { get; set; } } public class Product { public int ProductId { get; set; } public string Name { get; set; } public string CId { get; set; } public virtual Category Category { get; set; } }
Please suggest
When you change the relationship of the objects attached to the context by using one of the methods described above, Entity Framework needs to keep foreign keys, references, and collections in sync.
The [ForeignKey(name)] attribute can be applied in three ways: [ForeignKey(NavigationPropertyName)] on the foreign key scalar property in the dependent entity. [ForeignKey(ForeignKeyPropertyName)] on the related reference navigation property in the dependent entity.
Foreign Key Default ConventionThe Entity framework Core automatically creates the Foreign Key field in the database for us. But, if you add the DepartmentID property in the Employee entity, Entity Framework Core conventions will make use of that field and will not create another field.
Both these approaches should work:
public class Product { public int ProductId { get; set; } public string Name { get; set; } [ForeignKey("Category")] public string CId { get; set; } public virtual Category Category { get; set; } }
Or:
public class Product { public int ProductId { get; set; } public string Name { get; set; } public string CId { get; set; } [ForeignKey("CId")] public virtual Category Category { get; set; } }
ForeignKeyAttribute
is used to pair navigation property and foreign key property. It contains either the name of related navigation property or the name of related foreign key property.
You use entityconfigurations for this.
In the entityconfiguration, add this mapping to the category entityconfiguration:
HasMany<Product>(x => x.Products).WithRequired().HasForeignKey(x => x.CId);
You only need to map it on one of your classes and DbContext is clever enough to use it.
See this blog post for more info.
EDIT To do this using data annotations I believe the correct approach is as follows:
[RelatedTo(RelatedProperty="Products", Key="CId", RelatedKey="CategoryId")] public virtual Category Category { get; set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With