entity-framework-4.1 - 映射多对多关系

标签 entity-framework-4.1 ef-code-first

我在让 Entity Framework 处理我的数据模式中的多对多关系时遇到了一些麻烦。这是我的模型:

public class User
{
    public int UserId { get; set; }
    public int Username { get; set; }
    public IEnumerable<Customer> Customers { get; set; }
    ...
}

public class Customer
{
    public int CustomerId { get; set; }
    ...
}

public class CustomerUser
{
    public int CustomerUserId { get; set; }
    public int CustomerId { get; set; }
    public int UserId { get; set; }
    public DateTime CreatedTimestamp { get; set; }
    ...
}

这是映射:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<User>().HasKey(u => u.UserId).ToTable("Users");
        modelBuilder.Entity<Customer>().HasKey(c => c.CustomerId).ToTable("Customer");
        modelBuilder.Entity<CustomerUsers>().HasKey(cu => cu.CustomerUserId).ToTable("CustomerUsers");

        modelBuilder.Entity<CustomerUsers>()
            .HasRequired(cu => cu.User)
            .WithRequiredDependent()
            .Map(m =>
                {
                    m.ToTable("Users");
                    m.MapKey("CustomerUsers.UserId");
                });
}

我的数据库有一个 Users、Customers 和 CustomerUsers 表,其中的列与模型匹配。

我正在尝试执行以下查询:

result = (from u in context.Users
                      join customerUsers in context.CustomerUsers on u.UserId equals customerUsers.User.UserId
                      join customers in context.Customers on customerUsers.CustomerId equals customers.CustomerId into ps
                      select new
                      {
                          User = u,
                          Customers = ps
                      }).ToList().Select(r => { r.User.Customers = r.Customers.ToList(); return r.User; });

当我运行代码时,出现以下错误:

The Column 'CustomerUserId' specified as part of this MSL does not exist in MetadataWorkspace

谁能看出我的方法有什么问题?

谢谢!

我应该注意,我有意尝试不包含 Customer 或 User 类对 CustomerUsers 表的引用。大多数时候,CustomerUsers 表的负载并不重要,重要的是哪些客户与哪些用户相关联。在某些报告场景中,连接表中的附加信息是必需的,但由于这不是典型情况,我想避免通过这种额外的间接方式使模型困惑。

最佳答案

与其尝试将其映射为多对多,不如将其映射为两个一对多关系。请参阅本教程中多对多关系中对多对多连接表和负载的讨论:

http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-a-more-complex-data-model-for-an-asp-net-mvc-application

关于entity-framework-4.1 - 映射多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9470302/

相关文章:

c# - Entity Framework 4.1 Code First 创建多对多关系的方法

asp.net-mvc - 为什么 Entity Framework 不初始化我的导航集合?

c# - 您的 SQL 语法有错误,适用于 .net 的 mysql 连接器

asp.net-mvc - 如何首先在 EF 代码上使用 UnitOfWorkPattern 在 ASP.NET MVC 中实现 Quartz.NET 作业

c# - Entity Framework 包括 Where

entity-framework-4 - Entity Framework 4.1 和 SQL Compact 所需的程序集是什么?

database - "Cannot drop database because it is currently in use"。怎么修?

entity-framework-4.1 - LINQPad 方法访问异常

c# - EF 代码优先 - WithMany()

c# - 使用 GraphDiff 更新多对多关系会导致错误