[英]Linq updating a database, primary key
I have two tables. 我有两张桌子。 Document table and Version table.
文档表和版本表。 Both are identicle except the version table has an ID field and a documentID field.
两者都是相同的,除了版本表具有ID字段和documentID字段。 The document table has a documentId field.
文档表具有documentId字段。
I can correctly find the document but I cannot find the version table information because the id I am padding in it is trying to find this on the id field instead of the documentId field. 我可以正确找到文档,但是找不到版本表信息,因为我要填充的id试图在id字段而不是documentId字段上找到它。
public ActionResult ApproveDocument(int id = 0)
{
IPACS_Document ipacs_document = db.IPACS_Document.Find(id);
IPACS_Version ipacs_version = db.IPACS_Version.Find(id);
ipacs_version.dateApproved = System.DateTime.Now;
ipacs_version.approvedBy = User.Identity.Name.Split("\\".ToCharArray())[1];
ipacs_document.dateApproved = System.DateTime.Now;
ipacs_document.approvedBy = User.Identity.Name.Split("\\".ToCharArray())[1];
ipacs_document.revision = ipacs_version.revision;
db.SaveChanges();
return RedirectToAction("Approve");
}
So the ipacs_document
is found correctly because the id passed in 11 works. 因此正确找到了
ipacs_document
,因为在11中传递的id起作用。 However ipacs_version
doesn't find anything because it is trying to find id 11
instead of documentId 11
. 但是,
ipacs_version
找不到任何内容,因为它试图查找id 11
而不是documentId 11
。
If you're wondering on how to use Find
(DbSet<>) to engage composite keys
... 如果您想知道如何使用
Find
(DbSet <>)来使用composite keys
...
The Find method takes an array of objects as an argument.
Find方法将对象数组作为参数。 When working with composite primary keys, pass the key values separated by commas and in the same order that they are defined in the model.
使用复合主键时,请传递键值,这些键值之间应以逗号分隔,且顺序应与模型中定义的顺序相同。
http://msdn.microsoft.com/en-us/library/gg696418(v=vs.103).aspx http://msdn.microsoft.com/en-us/library/gg696418(v=vs.103).aspx
db.IPACS_Version.Find(id, documentid); // mind the order
And for anything more complex keep in mind that you could always use Linq queries, Where
eg 而对于什么想法没有更复杂的记住,你总是可以使用LINQ查询,
Where
如
db.IPACS_Version.Where(x => x.Id == id && x.DocumentId == docid && x.Flag == true);
Note: You could use the
query
,Where
(regardless of how your entities are made) -注意:您可以使用
query
,Where
(无论如何制作实体)-
but if yourkeys
are not set up properly (based on the comments) - I'd discourage you to go that way.但是,如果您的
keys
设置不正确 (基于评论),则我不鼓励您这样做。 Instead of a fast fix, make sure your tables, pk-s are set up as they should - as that's essential.确保快速安装表和pk-s而不是快速修复,这是必不可少的。 Then you can see which query is best for you (or just use Find if that's all you need).
然后,您可以查看哪个查询最适合您(或者,如果需要的话,只需使用“查找”即可)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.