【问题标题】:Entity Framework 4.1 Code First - Define many-to-many using data annotations onlyEntity Framework 4.1 Code First - 仅使用数据注释定义多对多
【发布时间】:2011-09-10 11:27:41
【问题描述】:

是否可以在实体框架 4.1(代码优先方法)中仅使用数据注释来定义多对多关系,而无需模型构建器?

例如:

Product = { Id, Name, ... }
Category = { Id, Name, ... }
ProductCategory = { ProductId, CategoryId }

你明白了。

我不想在上下文中使用两个多对一的中间实体ProductCategory,因为我没有任何其他数据,只有两个 FK。此外,我应该能够为中间表定义表名,以便与现有数据库一起使用。

【问题讨论】:

    标签: entity-framework data-annotations entity-framework-4.1 ef-code-first code-first


    【解决方案1】:

    可以使用默认约定或数据注释来定义多对多,但如果没有模型构建器,则无法将映射更改为连接表(表的名称和列)。简单的多对多:

    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; }
    }
    

    对于使用注释,您可以使用:

    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; }
    }
    

    如果您需要控制连接表到现有数据库的映射,您需要modelBuilder。数据注解不如 Fluent API 强大。

    【讨论】:

    • 谢谢,我按照你的建议做了,但还是不行。出于某种原因,当我尝试评估product.Categories 时,我得到了一个异常Invalid column name 'Category_Id'.\r\nInvalid column name 'Product_Id'.。这仅使用约定,即没有注释或流畅的 API。我的数据库表ProductsCategoriesProductIdCategoryId,中间没有下划线。为什么是下划线?它没有在任何地方记录为约定 AFAIK。 EF4.1 对于 1-M 和 M-1 关系不需要下划线(至少没有记录)。
    • Product_Id 和 Category_Id 是默认名称。如果您有现有的数据库并且您有不同的名称,则必须使用模型构建器将关系正确映射到您自己的表。
    • 你是对的。然而,在使用 1-M 关系的其他地方,它期望 FK 字段没有下划线(即ProductId)。这没有意义。实际上,这意味着如果我稍后在 ProductCategories 中间表中添加另一个字段(例如“Ord”),它将成为一个真正的实体,然后约定会抱怨它找不到字段“ProductId”。
    • @Shimmy:如果你需要在联结表中命名列,你必须使用 Fluent api。
    • @Shimmy:如果您想向 CustomeOrder 添加其他属性,它不再是联结表,因此为此实体创建一个新类并将您的客户和订单之间的多对多关系分解为两个单独的一对多的关系。您可以为此使用数据注释。
    猜你喜欢
    • 2011-08-13
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2011-04-06
    • 2013-06-02
    • 2012-05-15
    • 2011-08-01
    相关资源
    最近更新 更多