简体   繁体   English

如何在Entity Framework Core中将项目添加到多对多关系表中?

[英]How to add an item to a many-to-many relationship table in Entity Framework Core?

In my EF Core data model I have two table, the first table have an ICollection Navigation property to the second table and the second table also have an ICollection Navigation property to the first table. 在我的EF Core数据模型中,我有两个表,第一个表的第二个表具有ICollection Navigation属性,第二个表的第一个表也具有ICollection Navigation属性。

Data Model 资料模型

public class MyUser
{
    [Key]
    public string UserName { get; set; }
    public ICollection<Vote> Votes { get; set; }
    public virtual ICollection<PrivateUser> Rooms { get; set; }
}

public class PrivateUser
{
    [Key]
    public string RoomName { get; set; }
    public virtual ICollection<MyUser> Users { get; set; }
}

When I first add a MyUser only with name, 当我第一次添加仅具有名称的MyUser时,

 appuser = new MyUser
 {
      UserName = Context.User.Identity.Name
 };
 _context.MyUser.Add(appuser);
 _context.SaveChanges();

it's adding the user to the table correctly but when I try add a PrivateUser with an existing MyUser or I try to update the existing MyUser it gives NullReferenceException from the below code. 它正确地将用户添加到表,但是当我尝试添加PrivateUser与现有MyUser或我尝试更新现有MyUser它给人NullReferenceException从下面的代码。

PrivateUser roma = new PrivateUser() { RoomName = roomName};
try
{
    var user = new MyUser() { UserName = Context.User.Identity.Name };
    user.Rooms.Add(roma);
    _context.MyUsers.Attach(user).Property(u => u.Rooms).IsModified = true;
    roma.Users.Add(user);
    await _context.Rooms.AddAsync(roma);
    await _context.SaveChangesAsync();
}
catch(Exception ex)
{
    Console.WriteLine(ex.ToString());
}

I've also configured it in the ModelBuilder. 我还在ModelBuilder中配置了它。

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
     base.OnModelCreating(modelBuilder);
     modelBuilder.Entity<MyUser>().HasMany(u => u.Rooms);
     modelBuilder.Entity<PrivateUser>().HasMany(c => c.Users);

}

I'm a beginner on EF Core, can somebody please explain me how I can save the fields in correct way when the both table referencing themselves. 我是EF Core的初学者,有人可以向我解释当两个表都引用自己时如何以正确的方式保存字段。

After a long investigate I found there was no problem with my Entity Model the problem was because I solved that problem on my first Migration by using ModelBuilder 经过长时间的调查,我发现实体模型没有问题,原因是因为我在第一次Migration使用ModelBuilder解决了该问题

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<MyUser>().HasMany(u => u.Rooms);
   modelBuilder.Entity<PrivateUser>().HasMany(c => c.Users);
}

The problem was in my try block, see the correct code below. 问题出在我的try块中,请参见下面的正确代码。

try
{
    var user = new MyUser() { UserName = Context.User.Identity.Name };
    //here I was doing user.Rooms.Add(roma); where Romms is null
    roma.Rooms = new ICollection<PrivateUser>();
    //now we can add the room to Rooms
    user.Rooms.Add(roma);
    //and here was the below commented code from a Stackoverflow Answer
    //_context.MyUsers.Attach(user).Property(u => u.Rooms).IsModified = true;
    //we just have to use Update here;
    _context.MyUsers.Attach(user);
    _context.MyUsers.Update(user);
    roma.Users.Add(user);
    await _context.Rooms.AddAsync(roma);
    await _context.SaveChangesAsync();
}

Now everything fine as expected. 现在一切都按预期进行。 Thanks... 谢谢...

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

相关问题 如何在实体框架中添加或删除多对多关系? - How to add or remove a many-to-many relationship in Entity Framework? ASP .NET Core MVC Entity Framework - 如何访问由多对多关系产生的表? - ASP .NET Core MVC Entity Framework - How to get access to a table which is result of many-to-many relationship? 实体框架,代码优先,如何从多对多关系映射中向表添加主键? - Entity Framework, code-first, how to add primary key to table out of many-to-many relationship mapping? 实体框架核心:与同一实体的多对多关系 - Entity Framework Core: many-to-many relationship with same entity 实体框架核心多对多关系未从数据库加载 - Entity Framework Core Many-to-Many Relationship not loading from database 在 Entity Framework Core 中保存多对多关系 - Saving many-to-many relationship in Entity Framework Core 使用Entity Framework Core以多对多关系为数据库播种 - Seeding the database with a many-to-many relationship using Entity Framework Core Entity Framework Core:同一个对象的多对多关系 - Entity Framework Core: many-to-many relationship with the same object 实体框架核心与IdentityUser的多对多关系 - Entity Framework Core Many-to-Many relationship with IdentityUser 在Entity Framework Core中使用具有多对多关系的列表 - Using Lists with Many-to-Many relationship in Entity Framework Core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM