我正在使用Entity Framework 6 Code First编写代码与现有数据库交互,其中涉及到许多对多关系。在选择、插入和删除方面,这些关系都能够正常工作。但是,我遇到了一个问题,即EF会为现有的一对多关系添加额外的插入操作。
数据库结构如下图所示:
DbContext:
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);
}
DTOs:
[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?