【问题标题】:Accessing DB with Linq query使用 Linq 查询访问数据库
【发布时间】:2013-11-19 12:34:18
【问题描述】:

我正在学习带有实体框架的 MVC4。今天我弄清楚了如何更新联结表,现在我对 linq 的使用有点困惑。通常我用以下语句更新我的数据库。

db.Entity.Add(EntityViewModel);
               db.SaveChanges();

但是当我更新联结表时

 Entity EntityAttached = db.Entity.Where(x=> x.Id ==   EntityViewModle.Id).First();
   EntityViewModle.anotherEntities = EntityAttached.anotherEntities;
   EntityViewModle.anotherEntities.Clear(); EntityViewModle.anotherEntities.Add(anotherEntity);

db.Entry(EntityAttached).CurrentValues.SetValues(EntityViewModle);
db.SaveChanges();

它工作正常,但我并没有真正得到 db.Entry().CurrentValues.SetValues() 部分。请解释一下为什么我不能使用 .add() 并保存。否则有没有直接将数据输入到联结表?还是比上面描述的更简单的方法?

【问题讨论】:

    标签: c# linq entity-framework asp.net-mvc-4


    【解决方案1】:

    看起来此代码更新了现有实体。如果您使用 Add,那么您将从数据库中获取新 ID。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-16
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多