【发布时间】:2020-03-21 21:13:32
【问题描述】:
我目前正在学习如何通过简单的一对多设置使用 EF Core,其中 user 可以有多个 items。在从表中检索数据方面,这对于某些DTO 模型来说很好;但是,当我尝试通过 Postman 添加带有多个 items 的 user 时,我注意到对于每个 item,它已经多次复制了用户(即带有 3 个 items 的 user 将创建 3 个 @ 987654329@和3users):
邮递员 (POST)
{
"username": "xxx",
"dob": "xxx",
"location": "xxx",
"items":[{
"item": "xxx",
"category": "xxx",
"type": "xxx"
},
{
"item": "xxx",
"category": "xxx",
"type": "xxx"
},
{
"item": "xxx",
"category": "xxx",
"type": "xxx"
}]
}
上下文:
namespace TestWebApplication.Database
{
public class MyContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Items> Items { get; set; }
public MyContext(DbContextOptions<MyContext> options)
: base(options)
{
// erm, nothing here
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasMany(i => i.Items)
.WithOne(u => u.User);
}
public override int SaveChanges()
{
var entities = from e in ChangeTracker.Entries()
where e.State == EntityState.Added
|| e.State == EntityState.Modified
select e.Entity;
foreach (var entity in entities)
{
var validationContext = new ValidationContext(entity);
Validator.ValidateObject(entity, validationContext);
}
return base.SaveChanges();
}
}
}
控制器:
[HttpPost]
[Route("insertuseranditems")]
public ActionResult InsertUserAndItems(User user)
{
if (ModelState.IsValid)
{
using (MyContext myContext = _myContext as MyContext)
{
myContext?.Users?.Add(user);
int changes = myContext.SaveChanges();
if (changes > 0)
{
return Created("User saved", user);
}
}
}
return Accepted();
}
项目:
namespace TestWebApplication.Database
{
public class Items
{
[Key]
public int ItemId { get; set; }
public string Item { get; set; }
public string Category { get; set; }
public string Type { get; set; }
public virtual User User { get; set; }
}
}
用户:
namespace TestWebApplication.Database
{
public class User
{
[Key]
public int UserId { get; set; }
public string UserName { get; set; }
public string Dob { get; set; }
public string Location { get; set; }
public ICollection<Items> Items { get; set; }
}
}
【问题讨论】:
-
您是否有一些特定的用例需要为
SaveChanges方法编写自己的覆盖?从您的示例中,我认为不需要覆盖它,我想它只是让事情变得过于复杂。如果您想要一个简单的示例,可以完成添加具有多个项目的用户,那么我可以提供一个。 -
我已经尝试过您的代码,它只创建了一个包含三个项目的用户。请确保项目中的外键正确。
-
@XingZou 你的意思是在
Items模型中包含外键public int userid {get; set;}以及public virtual User User {get; set;}?我的代码中确实有这个,但把它去掉了,因为它在检索数据时没有任何区别。 -
OK。也许你可以尝试一个新的 mvc 项目或提供一个可重现的演示。