【问题标题】:Table with 2 foreign keys entity framework具有 2 个外键实体框架的表
【发布时间】:2011-07-25 04:40:22
【问题描述】:

我有一个包含 2 个外键的表。这些只是表格的元素。该表旨在创建其他 2 个表之间的关联。例如:表是Users_Products,只有2列是UserId和ProductID,都是外键。当我从数据库生成 EF 对象时,它没有创建 Users_Products 对象,它只是自动创建了导航属性。现在如何使用 EF 在我的 Users_Products 表中插入数据?

【问题讨论】:

    标签: c# sql sql-server entity-framework


    【解决方案1】:

    您可以获取一些用户对象并将产品添加到其导航属性中。

    User user = context.Users.Where(u => u.Id == 1);
    Product product = context.Products.Where(p => p.Id == 1);
    user.Products.Add(product);
    context.SaveChanges();
    

    【讨论】:

      【解决方案2】:

      有关演示如何在 EF 中使用多对多关系的代码示例,请参阅中的使用多对多关系部分 The Entity Framework 4.0 and ASP.NET – Getting Started Part 5.

      即 EF 4.0 / 数据库优先;有关使用 DbContext API 的示例,请参阅Updating Related Data with the Entity Framework in an ASP.NET MVC Application (6 of 10) 中的向讲师编辑页面添加课程作业

      【讨论】:

        【解决方案3】:
        using ( var ctx = new ...)
        {
          var user = new User();
          var product = new Product();
          user.Products.Add(product);
          ctx.Users.AddObject(user);
          ctx.SaveChanges();
        }
        

        【讨论】:

        • 不会只是在 Products 表中添加一个新项目吗?
        • user.Products.Add(product) 将在 Users_Products 表中添加条目。顺便说一句,如果您在此表中添加另一列(FK 除外),EF 也会为此表创建一个 EntityType。
        【解决方案4】:

        如果您想创建关系(将记录插入User_Products 表),您只需要在UserProduct 上使用导航属性:

        user.Products.Add(product);
        

        product.Users.Add(user);
        

        这意味着您必须至少在一侧具有导航属性才能创建关系。如果您从当前比赛中加载了实体,则可以使用@Pavel 描述的方法。

        如果您没有加载实体,或者您不想为了建立关系而对数据库进行两次查询,您可以使用以下解决方法:

        // Make dummy objects for records existing in your database
        var user = new User() { Id = 1 };
        var product = new Product() { Id = 1 };
        // Ensure that your context knows instances and does not track them as new or modified
        context.Users.Attach(user);
        context.Products.Attach(product);
        // Again make relation and save changes
        user.Products.Add(product);
        ctx.SaveChanges();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-08-05
          • 2011-05-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多