简体   繁体   English

在EF Core中的类之间添加多对多关系

[英]Adding Many To Many relationships between classes in EF Core

I'm working on a code-first database utilizing EF Core, and am having issues getting the relationships between entities quite right. 我正在使用EF Core开发代码优先的数据库,但是在使实体之间的关系变得正确时遇到了问题。

I have a model called Customer, that represents some basic customer information, as well as a model called User that represents a user of our site. 我有一个名为Customer的模型,该模型表示一些基本的客户信息,还有一个名为User的模型,该模型表示我们网站的用户。 These Users will have access to many Customers, and Customers will have many Users that have access to them (Many to Many relationship). 这些用户将有权访问许多客户,并且客户将具有许多对其具有访问权的用户(多对多关系)。

However, whenever I try to add existing Customers to a User's list, I get an error indicating that the Customer already exists. 但是,每当我尝试将现有客户添加到用户列表时,都会收到一条错误消息,表明该客户已经存在。

// retrieves the current list of Customers 
var current = GetCustomersByUserId(userId.ToString())?.Select(x => x.Id).ToList();
var toAdd = customers.Where(x => !current.Any(y => y.Equals(x.Id)));
customers.ForEach(x => x.Id = _data.Customers.First(y => y.SalesOrg.Equals(x.SalesOrg) && y.DistributionChannel.Equals(y.DistributionChannel) && y.Division.Equals(x.Division)).Id);
var affil = _data.Users.FirstOrDefault(x => x.Id.Equals(userId));
if (affil == null)
{
    affil = new User() { UserId = userId, Customers = customers, Id = Guid.NewGuid() };
    // Where the error occurs
    _data.Users.Add(affil);
}
else
{
    affil.Customers.AddRange(customers);
}
_data.SaveChanges();
return customers;

In the context OnModelCreating method I have the following: 在上下文OnModelCreating方法中,我具有以下内容:

modelBuilder.Entity<User>()
            .HasMany(x => x.Customers);

modelBuilder.Entity<Customer>()
            .HasMany(x => x.Users);

and in each of the classes, I reference the other as a property like so: 在每个类中,我将另一个作为属性引用,如下所示:

public List<Customer> Customers { get; set; }

public List<User> Users { get; set; }

Many-to-many relationships without an entity class to represent the join table are not yet supported on EF Core 2.1. EF Core 2.1尚不支持没有实体类来表示联接表的多对多关系。

But you can include an entity class for the join table and mapping two separate one-to-many relationships. 但是您可以为连接表包括一个实体类,并映射两个单独的一对多关系。 For example say you are creating a class UserCustomer your code in OnModelCreating would bee: 例如,假设您正在创建类UserCustomer,则在OnModelCreating中的代码将是:

    modelBuilder.Entity<UserCustomer>()
        .HasKey(t => new {....});

    modelBuilder.Entity<UserCustomer>()
        .HasOne(uc => uc.User)
        .WithMany(u => u.UsersCustomers )
        .HasForeignKey(.. => ....);

    modelBuilder.Entity<UserCustomer >()
        .HasOne(uc => uc.Customer)
        .WithMany(c => c.UsersCustomers)
        .HasForeignKey(.. => .....);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM