我有一個視圖模型,它只封裝了的一些數據庫模型屬性。視圖模型包含的這些屬性是我想要更新的唯一屬性。我希望其他的財產保持其價值。實體框架6.1更新記錄的子集
在我的研究中,我發現this答案似乎是完美的我的需求,但是,儘管我盡了最大的努力,我無法讓代碼按預期工作。
這裏是什麼,我想出了一個孤立的例子:
static void Main() {
// Person with ID 1 already exists in database.
// 1. Update the Age and Name.
Person person = new Person();
person.Id = 1;
person.Age = 18;
person.Name = "Alex";
// 2. Do not update the NI. I want to preserve that value.
// person.NINumber = "123456";
Update(person);
}
static void Update(Person updatedPerson) {
var context = new PersonContext();
context.Persons.Attach(updatedPerson);
var entry = context.Entry(updatedPerson);
entry.Property(e => e.Name).IsModified = true;
entry.Property(e => e.Age).IsModified = true;
// Boom! Throws a validation exception saying that the
// NI field is required.
context.SaveChanges();
}
public class PersonContext : DbContext {
public DbSet<Person> Persons { get; set; }
}
public class Person {
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int Age { get; set; } // this is contrived so, yeah.
[Required]
public string NINumber { get; set; }
}
我在做什麼錯?
爲什麼你連接的人提供的解決方案來解決?通常,當我使用實體框架時,我只需檢索記錄,修改其屬性並執行SaveChanges();類似於:Person person = context.People.First(); person.Name =「John」; context.SaveChanges(); – Areks
因爲這實際上需要對數據庫+進行兩次查詢,所以我正在使用通用存儲庫。 –
這不是一個真正的通用存儲庫,但無論如何,@Areks的+1表示。如果你擔心2個查詢,那麼你有其他問題 – mituw16