0

我正在尝试更新一个实体,但是当我调用 save changes 时没有任何反应。这是我如何附加实体的代码。顺便说一下,我正在使用 EF6.1 和 MVC5.1

var entity = db.Entity.Attach(existingEntity);
entity = new Entity(args0, args1, args2)
entity.Id = existingEntity.Id;
db.SaveChanges()

这是实体类:

 public class Entity : Entity
 {
    public int Id { get; set; }

    public string PropertyA { get; private set; }
    public string PropertyB { get; private set; }
    public string PropertyC { get; private set; }
 }

 public Entity(string args0, string args1, string args2)
 {
      this.PropertyA = args0;
      this.PropertyB = args1;
      this.PropertyC = args2;
 }

请注意,我确实将属性设置器设置为私有,因为我在类中有一些内部工作。我在想 EF 无法更新实体的原因是因为我实例化了一个新实体,尽管我确实设置了它的主键。我也尝试将状态更改为已修改,但它只是运行“更新脚本”,但它并没有真正反映我对每个属性所做的更改

这种情况的任何可能的解决方案?

4

2 回答 2

0

I am myself new to MVC and EF. But here goes.

Are you not mixing up your DAL and BLL by using private set?

Also, when you already have the existing entity why cant you just update the properties for entity directly? The way your class has been set up it can only be created, not modified.

Lastly, I think you have to explicitly tell EF that existingEntity has been modified.

于 2014-03-26T19:40:49.267 回答
0
var entity = new Entity(args0, args1, args2)
entity.Id = existingEntity.Id;
db.Entity.Attach(entity);
db.SaveChanges();
于 2014-03-27T02:11:04.697 回答