【问题标题】:Duplicate Foreign Key entries being created on insert - EF Core and Web Api 3.1插入时创建的重复外键条目 - EF Core 和 Web Api 3.1
【发布时间】:2020-03-21 21:13:32
【问题描述】:

我目前正在学习如何通过简单的一对多设置使用 EF Core,其中 user 可以有多个 items。在从表中检索数据方面,这对于某些DTO 模型来说很好;但是,当我尝试通过 Postman 添加带有多个 itemsuser 时,我注意到对于每个 item,它已经多次复制了用户(即带有 3 个 itemsuser 将创建 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 项目或提供一个可重现的演示。

标签: asp.net-core ef-core-3.1


【解决方案1】:

我重新访问了我的代码并将我的 Items.cs 模型更改为:

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; }

        [ForeignKey("User")] // added this
        public int? UserId { get; set; } // added this

        public virtual User User { get; set; }
    }
}

现在,当我通过 Postman 发送上述 json 时,我得到了多个具有相同用户作为外键的项目。

下面的网站似乎有帮助:

The ForeignKey Attribute

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    相关资源
    最近更新 更多