gpt4 book ai didi

c# - Linq更新数据库,主键

转载 作者:太空宇宙 更新时间:2023-11-03 13:44:05 24 4
gpt4 key购买 nike

我有两张 table 。文档表和版本表。除了版本表有一个 ID 字段和一个 documentID 字段外,两者完全相同。文档表有一个 documentId 字段。

我可以正确找到文档,但找不到版本表信息,因为我在其中填充的 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");
}

因此 ipacs_document 被正确找到,因为 11 中传递的 id 有效。但是 ipacs_version 没有找到任何东西,因为它试图找到 id 11 而不是 documentId 11

最佳答案

如果您想知道如何使用 Find (DbSet<>) 来使用 composite keys...

The Find method takes an array of objects as an argument. 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

db.IPACS_Version.Find(id, documentid); // mind the order

对于任何更复杂的事情,请记住您始终可以使用 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) -
but if your keys are not set up properly (based on the comments) - I'd discourage you to go that way. Instead of a fast fix, make sure your tables, pk-s are set up as they should - as that's essential. Then you can see which query is best for you (or just use Find if that's all you need).

关于c# - Linq更新数据库,主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15955470/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com