【问题标题】:Entity Framework Code First Existing Database set EntityState.Unchanged on Many-to-ManyEntity Framework Code First Existing Database set EntityState.Unchanged on Many-to-Many
【发布时间】:2014-12-29 19:32:51
【问题描述】:

我有一个现有的数据库,我正在使用 Entity Framework 6 Code First 进行编码。我有一个适用于选择、插入和删除的多对多关系。我遇到了 EF 为现有关系向多对多表添加额外插入的问题。

架构:

数据库上下文:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
       Database.SetInitializer<MainContext>(null);

       modelBuilder.Entity<DocumentType>()
                .HasMany(u => u.DocumentStatuses)
                .WithMany()
                .Map(m =>
                {
                    m.MapLeftKey("DOCUMENT_TYPE_ID");
                    m.MapRightKey("DOCUMENT_STATUS_ID");
                    m.ToTable("DOCUMENT_TYPES_DOCUMENT_STATUSES");
                });

       base.OnModelCreating(modelBuilder);
    } 

DTO:

    [Table("DOCUMENT_TYPES")]
    public class DocumentType
    {
        [Key]
        [Column("DOCUMENT_TYPE_ID")]
        public int? Id { get; set; }

        [Required]
        [Column("TYPE_NAME")]
        public string TypeName { get; set; }

        [Required]
        [Column("IS_ACTIVE")]
        public bool IsActive { get; set; }

        [Display(Name = "Updated By")]
        [Column("LAST_UPDATED_BY")]
        public string LastUpdatedBy { get; set; }

        [Display(Name = "Updated Date")]
        [Column("LAST_UPDATED_DATE")]
        public DateTimeOffset? LastUpdatedDate { get; set; }

        public virtual List<DocumentStatus> DocumentStatuses { get; set; } 

        public DocumentType()
        {
            DocumentStatuses = new List<DocumentStatus>();
        }
    }

[Table("DOCUMENT_STATUSES")]
public class DocumentStatus
{
    [Key]
    [Column("DOCUMENT_STATUS_ID")]
    public int? Id { get; set; }

    [Required]
    [Column("STATUS_NAME")]
    public string StatusName { get; set; }

    [Required]
    [Column("IS_COMPLETE")]
    public bool IsComplete { get; set; }

    [Required]
    [Column("IS_ACTIVE")]
    public bool IsActive { get; set; }

    [Display(Name = "Updated By")]
    [Column("LAST_UPDATED_BY")]
    public string LastUpdatedBy { get; set; }

    [Display(Name = "Updated Date")]
    [Column("LAST_UPDATED_DATE")]
    public DateTimeOffset? LastUpdatedDate { get; set; }
}

存储库更新:

    public bool Update(DocumentType entity, string updatedBy)
            {
                DateTimeOffset updatedDateTime = DateTimeOffset.Now;

                entity.LastUpdatedBy = updatedBy;
                entity.LastUpdatedDate = updatedDateTime;

                using (var db = new MainContext())
                {
                    db.DocumentTypes.Add((DocumentType)entity);
                    db.Entry(entity).State = EntityState.Modified;

                    foreach (var item in entity.DocumentStatuses)
                    {
                        if (item.Id != null)
                            db.Entry(item).State = EntityState.Unchanged;
                    }

                    db.SaveChanges();
                }

                return true;
            }

循环包含:

    if (item.Id != null)
     db.Entry(item).State = EntityState.Unchanged;

阻止添加新记录,但 EF 仍尝试将现有多对多记录的副本插入 DOCUMENT_TYPES_DOCUMENT_STATUSES。

单元测试:

        [TestMethod()]
        public void UpdateTest()
        {
            DocumentTypeRepository documentTypeRepository = new DocumentTypeRepository();
            DocumentType type = NewDocumentType(true);
            DocumentType typefromDb;
            string updatedBy = "DocumentTypeRepositoryTests.UpdateTest";
            bool actual;

            type.IsActive = true;
            type.TypeName = RandomValues.RandomString(18);
            type.DocumentStatuses.Add(DocumentStatusRepositoryTests.NewDocumentStatus(true));

            actual = documentTypeRepository.Update(type, updatedBy);
            Assert.AreEqual(true, actual);

            typefromDb = documentTypeRepository.GetById((int)type.Id);
            Assert.AreEqual(type.DocumentStatuses.Count, typefromDb.DocumentStatuses.Count);
        }

如果多对多表已经存在,如何将其设置为 EntityState.Unchanged?

【问题讨论】:

    标签: c# entity-framework entity-framework-6


    【解决方案1】:

    尝试替换

    db.DocumentTypes.Add((DocumentType)entity);
    db.Entry(entity).State = EntityState.Modified;
    

    与

    db.Entry(entity).State = entity.Id == null 
        ? EntityState.Added
        : EntityState.Modified;
    

    在对分离的实体进行 CRUD 操作时,不使用 DbSet 操作而只操作实体状态条目会更容易。至少,它可以减少错误。

    【讨论】:

    • 我在 using 的上方确实有一行检查了 id: if (entity.Id == null) throw new InvalidOperationException("DocumentTypeId cannot be null on updates.");我删除了它以保持示例更清洁。有趣的是,我通过您的示例绕过了错误,但它不会保存添加到列表中的任何新状态,只是保留旧状态。
    • 关键部分是删除 .Add
    • 我在上面添加了我的单元测试,当我向列表中添加一个新的状态项并更新(使用新代码)时,它不会将新项添加到多对-很多表。所以最后一个断言失败了,因为它只有第一个状态而不是两个。
    • @Josh Frank 是对的,但所涉及的内容比表面上看到的要多。我在一个答案中解释了它。没有评论。
    【解决方案2】:

    这里有两点需要注意:

    1. 当你Add一个实体到一个上下文时,该实体拥有的整个对象图被标记为Added。

    2. 在任何关联中,这也将关联标记为新关联。然而,虽然在 1:n 或 1:1 关联中,关联状态会随着一端状态的改变而改变,但在多对多关联中,关联的一部分是隐藏的,并且将始终保持Added。 (实际上,多对多关联是 1:n:1 关联,n 部分在您的代码中不可见)。

    所以这个说法...

    db.DocumentTypes.Add(entity);
    

    使关联获得Added 状态,以及随后的...

    db.Entry(entity).State = EntityState.Modified;
    

    不再改变这一点。

    您必须确保现有DocumentType 的状态永远不会更改为Added,您可以通过检查其Id 值来做到这一点,就像您为DocumentStatus 所做的那样。

    另外,您必须更改设置DocumentStatuses 状态的方式:

    foreach (var item in entity.DocumentStatuses)
    {
        db.Entry(item).State = item.Id != null
                                   ? EntityState.Unchanged
                                   : EntityState.Added;
    }
    

    【讨论】:

    • 这是有道理的。顺便说一句,演员表是复制和粘贴,我有其他使用接口的对象,所以这就是我演员表的原因。所以问题是弗兰克的改变是因为它不再尝试向表插入重复的 1:n:1 关系。问题是,如果我向 DocumentType.DocumentStatus 添加另一个 DocumentStatus,然后调用此更新方法,它不会为新添加的 DocumentStatus 创建 1:n:1 记录。所以我们解决了一个问题,但又创造了一个新问题。
    • 我也有同样的想法并尝试过。但是如果你看我上面的单元测试,我不是添加一个新的状态,而是添加一个与现有状态的新的 1:n:1 关系。因此,项目的 EntityState 状态将具有一个 Id,因此它始终是 EntityState.Unchanged,这是有道理的,因为它已经存在。
    • 我看不到那里到底发生了什么,但至少这是前进的方向。它适用于我现在正在测试的简单多对多模式。
    • 如果你从列表中删除一个项目并保存,我们有同样类型的问题,它基本上没有删除1:n:1的关系。
    • 您必须在 DocumentType 之后删除一个项目,并且它的状态附加到上下文中,否则更改跟踪器将永远不会知道曾经有一个项目要删除。跨度>
    猜你喜欢
    • 2012-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    • 1970-01-01
    • 2013-09-11
    • 1970-01-01
    相关资源
    最近更新 更多