C# 更新类或viewmodel的集合
我有一个包含两个类的viewModelC# 更新类或viewmodel的集合,c#,asp.net-mvc,entity-framework,viewmodel,C#,Asp.net Mvc,Entity Framework,Viewmodel,我有一个包含两个类的viewModel public class vwbooking { public booking bookings { get; set; } public IEnumerable<trace> traces { get; set; } } 这是我的db上下文类 public class salesContext : DbContext { public salesContext() : base() { Con
public class vwbooking
{
public booking bookings { get; set; }
public IEnumerable<trace> traces { get; set; }
}
这是我的db上下文类
public class salesContext : DbContext
{
public salesContext() : base()
{
Configuration.LazyLoadingEnabled = true;
}
public salesContext(string Connection) : base(Connection)
{
Configuration.LazyLoadingEnabled = true;
}
public DbSet<booking> bookings { get; set; }
public DbSet<trace> traces { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<booking>().HasKey(e => e.bookingid);
modelBuilder.Entity<trace>().HasKey(e => e.traceid);
}
}
公共类salesContext:DbContext
{
公共salesContext():base()
{
Configuration.LazyLoadingEnabled=true;
}
公共salesContext(字符串连接):基本(连接)
{
Configuration.LazyLoadingEnabled=true;
}
公共数据库集预订{get;set;}
公共数据库集跟踪{get;set;}
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
基于模型创建(modelBuilder);
modelBuilder.Entity().HasKey(e=>e.bookingid);
modelBuilder.Entity().HasKey(e=>e.traceid);
}
}
更新模型的代码是:
db.Attach(vwbooking.bookings)
db.ObjectStateManager.ChangeObjectState(vwbooking.bookings, System.Data.EntityState.Modified)
vwbooking.traces.ToList().ForEach(
t =>
{
db.Attach(t);
db.ObjectStateManager.ChangeObjectState(t, System.Data.EntityState.Modified);
}
);
db.SaveChanges();
在编辑控制器中尝试此代码这是因为vwbooking不是DbContext中的模型。它只是保存数据以便视图显示。你必须更新vwbooking属性,因为它们是你的模型。好吧-我想我理解,但我想这就是我在做的?我该怎么做呢?我在下面的回答中添加了更多细节。这非常接近。预订部分将更新。跟踪部件抛出“值不能为null。参数名称:源”错误。我还在努力解决这个问题,我还没弄明白。即使这样也会产生同样的错误。。。ForEach(t=>{Response.Write(“qwer”);});我将根据您的反馈开始一个新的线程。谢谢你的帮助。新线程是
public class salesContext : DbContext
{
public salesContext() : base()
{
Configuration.LazyLoadingEnabled = true;
}
public salesContext(string Connection) : base(Connection)
{
Configuration.LazyLoadingEnabled = true;
}
public DbSet<booking> bookings { get; set; }
public DbSet<trace> traces { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<booking>().HasKey(e => e.bookingid);
modelBuilder.Entity<trace>().HasKey(e => e.traceid);
}
}
db.Attach(vwbooking.bookings)
db.ObjectStateManager.ChangeObjectState(vwbooking.bookings, System.Data.EntityState.Modified)
vwbooking.traces.ToList().ForEach(
t =>
{
db.Attach(t);
db.ObjectStateManager.ChangeObjectState(t, System.Data.EntityState.Modified);
}
);
db.SaveChanges();