Bor*_* B. 8 entity-framework code-first data-annotations ef-code-first entity-framework-4.1
是否可以仅使用数据注释在Entity Framework 4.1(Code First方法)中定义多对多关系,而无需使用模型构建器?
例如,类似于:
Product = { Id, Name, ... }
Category = { Id, Name, ... }
ProductCategory = { ProductId, CategoryId }
Run Code Online (Sandbox Code Playgroud)
你得到了照片.
我不希望ProductCategory在上下文中有两个多对一的中间实体,因为我没有任何额外的数据,只有两个FK.此外,我应该能够为中间表定义表名,以便与现有数据库一起使用.
Lad*_*nka 11
可以使用默认约定或数据注释定义多对多,但是如果没有模型构建器,则无法更改映射到联结表(表的名称和列).简单的多对多:
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; }
}
Run Code Online (Sandbox Code Playgroud)
对于使用注释,您可以使用:
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; }
}
Run Code Online (Sandbox Code Playgroud)
如果需要控制联结表到现有数据库的映射,则需要modelBuilder.数据注释不如流畅的API强大.