简体   繁体   中英

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.

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. 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:

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.

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:

    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(.. => .....);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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