Entity Framework 4.1 Code First - Define many-to-many using data annotations only

时间秒杀一切 提交于 2019-12-04 03:41:58

It is possible to define many-to-many with default conventions or with data annotations but it is not possible to change mapping to junction table (table's name and columns) without model builder. Simple many-to-many:

public class Product
{
    public int Id { get; set; }
    public virtual ICollection<Category> Categories { get; set; }
}

public class Category
{
    public int Id { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

For using annotations you can use:

public class Product
{
    [Key]
    public int Id { get; set; }
    [InverseProperty("Products")]
    public virtual ICollection<Category> Categories { get; set; }
}

public class Category
{
    [Key] 
    public int Id { get; set; }
    [InverseProperty("Categories")]
    public virtual ICollection<Product> Products { get; set; }
}

If you need to control mapping of junction table to existing database you need modelBuilder. Data annotations are not as powerful as fluent API.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!