[英]Attempting to update database using Entity Framework Code First
I am trying to update a database entry using entity framework. 我正在尝试使用实体框架更新数据库条目。 The entities are as follows:
实体如下:
public partial class Test
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid identity { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public TestRef Colour { get; set; }
}
public class TestRef
{
public int id { get; set; }
public string favColor { get; set; }
}
and the edit ActionResult in the relevant Controller is as follows: 并且相关Controller中的编辑ActionResult如下:
public ActionResult Edit([Bind(Include = "identity,Name,Age,Colour")] Test test)
{
if (ModelState.IsValid)
{
test.Colour = db.TestRefs.Find(test.Colour.id);
db.Tests.Attach(test);
db.Entry(test).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(test);
}
So here, Edit seems to work for all the properties in Test except for Colour (in that all the other properties get updated, but Colour remains as it was before, with no change). 所以在这里,Edit似乎适用于Test中除Color之外的所有属性(因为所有其他属性都得到了更新,但Color仍然保持原样,没有任何变化)。 I am assuming this is because it is an association, but I can't for the life of me figure out why.
我假设这是因为它是一个联想,但我不能为我的生活找出原因。
First, tell EF that TestRef
have a key: 首先,告诉EF
TestRef
有一个密钥:
public class TestRef
{
[Key] /* <--- */
/*[DatabaseGenerated( ??? )] Does value generated by database? */
public int id { get; set; }
public string favColor { get; set; }
}
Second, make reference be a foreign key: 其次,将引用作为外键:
public partial class Test
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid identity { get; set; }
public string Name { get; set; }
public int Age { get; set; }
[ForeignKey("TestRefID")] /* <--- */
public TestRef Colour { get; set; }
}
Name TestRefID
in code above is just example. 上面代码中的名称
TestRefID
就是一个例子。 Put there name of FK column from your database. 在数据库中输入FK列的名称。 You do have FK column in database for this relation, isn't it?
对于这种关系,你在数据库中有FK列,不是吗?
Also, if you need lazy loading, make Colour
property virtual
: 此外,如果您需要延迟加载,请将
Colour
属性virtual
:
...
[ForeignKey("TestRefID")]
public virtual TestRef Colour { get; set; }
...
EF will make a direved type and for all virtual reference properties it will implement lazy-loading logic. EF将成为一种强制类型,对于所有虚拟引用属性,它将实现延迟加载逻辑。 It's default behavior until you disable it in db context settings:
在db上下文设置中禁用它之前,它是默认行为:
yourDataContext.ContextOptions.LazyLoadingEnabled = false;
By the way, it's not a good idea to use GUID as primary key. 顺便说一下,使用GUID作为主键并不是一个好主意。 Look here for cons and pros.
在这里寻找利弊和专业人士。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.