C# 无法使用实体框架删除和插入M-M关系数据
我有如下M-M关系数据结构。但是,我无法删除和插入该记录。我在谷歌上搜索并使用了来自和的样本 公司:C# 无法使用实体框架删除和插入M-M关系数据,c#,.net,entity-framework,many-to-many,dbcontext,C#,.net,Entity Framework,Many To Many,Dbcontext,我有如下M-M关系数据结构。但是,我无法删除和插入该记录。我在谷歌上搜索并使用了来自和的样本 公司: [Serializable] public class Company : Base.BaseEntity { public long CompanyId { get; set; } public string CompanyName { get; set; } public string TimeZone { get; set; } public string
[Serializable]
public class Company : Base.BaseEntity
{
public long CompanyId { get; set; }
public string CompanyName { get; set; }
public string TimeZone { get; set; }
public string Address { get; set; }
public long? CityId { get; set; }
public long? StateId { get; set; }
public int Zip { get; set; }
public string Telephone { get; set; }
public string Fax { get; set; }
public string EmailAddress { get; set; }
public string FederalEin { get; set; }
public string WebPage { get; set; }
public string StateEmployerNumber { get; set; }
public long? AdministratorId { get; set; }
public string OfflineAdlLockoutTime { get; set; }
public bool? IsAllowWindowsAuthentication { get; set; }
public virtual ICollection<CommunityType> CommunityTypeList { get; set; }
}
[Serializable]
public class CommunityType : Base.BaseEntity
{
public long CommunityTypeId { get; set; }
public string CommunityTypeName { get; set; }
public string Description { get; set; }
public virtual ICollection<Company> CompanyList { get; set; }
}
[可序列化]
公共类公司:Base.BaseEntity
{
公共长公司ID{get;set;}
公共字符串CompanyName{get;set;}
公共字符串时区{get;set;}
公共字符串地址{get;set;}
公共long?CityId{get;set;}
公共long?StateId{get;set;}
公共int Zip{get;set;}
公用字符串电话{get;set;}
公共字符串传真{get;set;}
公共字符串电子邮件地址{get;set;}
公共字符串FederalEin{get;set;}
公共字符串网页{get;set;}
公共字符串StateEmployerNumber{get;set;}
公共长?管理员ID{get;set;}
脱机锁定时间{get;set;}的公共字符串
公共bool?isAllowIndowsAuthentication{get;set;}
公共虚拟ICollection社区类型列表{get;set;}
}
社区类型:
[Serializable]
public class Company : Base.BaseEntity
{
public long CompanyId { get; set; }
public string CompanyName { get; set; }
public string TimeZone { get; set; }
public string Address { get; set; }
public long? CityId { get; set; }
public long? StateId { get; set; }
public int Zip { get; set; }
public string Telephone { get; set; }
public string Fax { get; set; }
public string EmailAddress { get; set; }
public string FederalEin { get; set; }
public string WebPage { get; set; }
public string StateEmployerNumber { get; set; }
public long? AdministratorId { get; set; }
public string OfflineAdlLockoutTime { get; set; }
public bool? IsAllowWindowsAuthentication { get; set; }
public virtual ICollection<CommunityType> CommunityTypeList { get; set; }
}
[Serializable]
public class CommunityType : Base.BaseEntity
{
public long CommunityTypeId { get; set; }
public string CommunityTypeName { get; set; }
public string Description { get; set; }
public virtual ICollection<Company> CompanyList { get; set; }
}
[可序列化]
公共类CommunityType:Base.BaseEntity
{
公共长社区类型ID{get;set;}
公共字符串CommunityTypeName{get;set;}
公共字符串说明{get;set;}
公共虚拟ICollection公司列表{get;set;}
}
我有一个回购方法
public void Persist<TEntity>(TEntity entity, long id, bool isHardDelete = false) where TEntity : BaseEntity
{
try
{
if (!isHardDelete)
{
var item = entity as BaseEntity;
if (id <= 0)
{
Entry(entity).State = EntityState.Added;
Set<TEntity>().Add(entity);
}
else
{
Set<TEntity>().Attach(entity); // I have an error here
Entry(entity).State = EntityState.Modified;
}
}
else
{
Entry(entity).State = EntityState.Deleted;
Set<TEntity>().Attach(entity);
}
}
catch (DbEntityValidationException dbEx)
{
throw new Exception(GetFullErrorText(dbEx), dbEx);
}
}
public int SaveChanges(long id = 0)
{
try
{
ChangeTracker.Entries().ForEach(entity =>
{
var baseDto = entity.Entity as BaseEntity;
if (baseDto == null) return;
if (id <= 0)
{
baseDto.CreatedOn = baseDto.UpdatedOn = DateTime.Now;
baseDto.CreatedBy = baseDto.UpdatedBy = 1;
}
else
{
baseDto.UpdatedBy = 1;
baseDto.UpdatedOn = DateTime.Now;
}
});
return base.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
throw new Exception(GetFullErrorText(dbEx), dbEx);
}
}
公司报告
public void Persist(Company entity)
{
using (var dbContext = ServiceLocator.Current.GetInstance<IDbContext>())
{
// Here I am going to save the company information (may be edited some properties).
dbContext.Persist(entity, entity.CompanyId);
dbContext.SaveChanges(entity.CompanyId);
// Here I am trying to delete the existing community types and insert a new community types.
var existingCompany = dbContext.Table<Company>().Include(i => i.CommunityTypeList).AsNoTracking().Where(s => s.CompanyId == entity.CompanyId).FirstOrDefault();
var deletedCommunityTypes = existingCompany.CommunityTypeList.Except(entity.CommunityTypeList, x => x.CommunityTypeId).ToList();
var addedCommunityTypes = entity.CommunityTypeList.Except(existingCompany.CommunityTypeList, x => x.CommunityTypeId).ToList();
deletedCommunityTypes.ForEach(c => existingCompany.CommunityTypeList.Remove(c));
foreach (var c in addedCommunityTypes)
{
existingCompany.CommunityTypeList.Add(c);
}
dbContext.Persist(existingCompany, existingCompany.CompanyId);
dbContext.SaveChanges(existingCompany.CompanyId);
}
}
public void Persist(公司实体)
{
使用(var dbContext=ServiceLocator.Current.GetInstance())
{
//在这里,我将保存公司信息(可能会编辑一些属性)。
Persist(entity,entity.CompanyId);
dbContext.SaveChanges(entity.CompanyId);
//在这里,我试图删除现有的社区类型并插入一个新的社区类型。
var existingCompany=dbContext.Table().Include(i=>i.CommunityTypeList).AsNoTracking().Where(s=>s.CompanyId==entity.CompanyId).FirstOrDefault();
var deletedCommunityTypes=existingCompany.CommunityTypeList.Exception(entity.CommunityTypeList,x=>x.CommunityTypeId).ToList();
var addedCommunityTypes=entity.CommunityTypeList.Exception(existingCompany.CommunityTypeList,x=>x.CommunityTypeId).ToList();
deletedCommunityTypes.ForEach(c=>existingCompany.CommunityTypeList.Remove(c));
foreach(addedCommunityTypes中的var c)
{
现有公司。社区类型列表。添加(c);
}
dbContext.Persist(existingCompany,existingCompany.CompanyId);
dbContext.SaveChanges(existingCompany.CompanyId);
}
}
我的DB上下文方法是
public void Persist<TEntity>(TEntity entity, long id, bool isHardDelete = false) where TEntity : BaseEntity
{
try
{
if (!isHardDelete)
{
var item = entity as BaseEntity;
if (id <= 0)
{
Entry(entity).State = EntityState.Added;
Set<TEntity>().Add(entity);
}
else
{
Set<TEntity>().Attach(entity); // I have an error here
Entry(entity).State = EntityState.Modified;
}
}
else
{
Entry(entity).State = EntityState.Deleted;
Set<TEntity>().Attach(entity);
}
}
catch (DbEntityValidationException dbEx)
{
throw new Exception(GetFullErrorText(dbEx), dbEx);
}
}
public int SaveChanges(long id = 0)
{
try
{
ChangeTracker.Entries().ForEach(entity =>
{
var baseDto = entity.Entity as BaseEntity;
if (baseDto == null) return;
if (id <= 0)
{
baseDto.CreatedOn = baseDto.UpdatedOn = DateTime.Now;
baseDto.CreatedBy = baseDto.UpdatedBy = 1;
}
else
{
baseDto.UpdatedBy = 1;
baseDto.UpdatedOn = DateTime.Now;
}
});
return base.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
throw new Exception(GetFullErrorText(dbEx), dbEx);
}
}
public void Persist(tenty-entity,long-id,bool-isHardDelete=false),其中tenty:BaseEntity
{
尝试
{
如果(!isHardDelete)
{
var项目=作为基本实体的实体;
如果(id)
{
var baseDto=实体。实体作为BaseEntity;
if(baseDto==null)返回;
如果(id)您传递到方法Persist()
中的实体是通过db调用检索的,例如var entitiy=db.Thingy.First(pred)
,那么除非您设置了AsNoTracking()
,否则它已经附加到上下文,您不需要再次附加?@Wurd我使用了AsNoTracking()
也是。但是,如果不包含Attach()
?@Wurd,则不会在实体上保存luckDo更改。