我正在使用代码优先(EF5)方法来创建我的域类。我执行查询以拉出父记录w /一个孩子的集合。我需要编辑我的父级并对子级执行CRUD操作。
在保存我的对象(父/子)时,实体状态是Detached的问题,因此如果修改,删除或插入的对象没有额外的逻辑,我现在不会。
如何启用EF以继续跟踪我的实体或不分离我的实体?
这是我的代码:
public class myDbContext : DbContext
{
#region ConnectionStrings
public myDbContext()
: base(ConfigurationManager.ConnectionStrings[ConfigurationManager.AppSettings["ActiveDB_my"]].ToString())
{
this.Configuration.LazyLoadingEnabled = true;
Database.SetInitializer<myDbContext>(null);
//this.Configuration.ProxyCreationEnabled = true;
//this.Configuration.AutoDetectChangesEnabled = true;
}
#endregion
#region EntityFramework
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Entity Framework Configurations
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
//Load Entity Configurations
dbomyAnotations.Load(ref modelBuilder);
base.OnModelCreating(modelBuilder);
}
#endregion
#region EntityRegistrations
//Client
public DbSet<ClientLocation> ClientLocations { get; set; }
//Templates
public DbSet<Template> Templates { get; set; }
#endregion
}
namespace App.myTrak.BL
{
public class Templates
{
public static ClientLocation getTemplatesForClientLocation(int clientLocationId)
{
ClientLocation entity = null;
using (myDbContext db = new myDbContext())
{
entity = db.ClientLocations
.Where(c => c.ClientLocationId == clientLocationId)
.Include(t => t.Templates)
.FirstOrDefault();
}
return entity;
}
public static void saveForTemplates(ClientLocation clientLocations)
{
int Id = clientLocations.ClientLocationId;
var db = new myDbContext();
//Client Location
db.ClientLocations.Attach(clientLocations);
db.Entry(clientLocations).State = System.Data.EntityState.Unchanged;
db.Entry(clientLocations).Property(x => x.ShowPresoldProducts).IsModified = true;
//App Templates
foreach (var template in clientLocations.Templates)
{
db.Templates.Attach(template);
db.Entry(template).State = System.Data.EntityState.Unchanged;
if (template.DeleteDate != null)
{
db.Entry(template).Property(x => x.DeleteUserId).IsModified = true;
db.Entry(template).Property(x => x.DeleteDate).IsModified = true;
template.DeleteDate = Shared.Common.DateTimeUTC();
}
else if (template.TemplateId == 0)
db.Entry(template).State = System.Data.EntityState.Added;
else
{
//Modified
db.Entry(template).Property(x => x.TemplateName).IsModified = true;
db.Entry(template).Property(x => x.Description).IsModified = true;
db.Entry(template).Property(x => x.AppTypeId).IsModified = true;
db.Entry(template).Property(x => x.ModifyUserId).IsModified = true;
db.Entry(template).Property(x => x.ModifyDate).IsModified = true;
template.ModifyDate = Shared.Common.DateTimeUTC();
template.ModifyUserId = CurrentUserId;
}
}
db.SaveChanges();
db.Database.Connection.Close();
}
}
}