gpt4 book ai didi

c# - Entity Framework 外键(或缺少外键)

转载 作者:太空宇宙 更新时间:2023-11-03 11:54:40 25 4
gpt4 key购买 nike

所以我一直在倾注这段代码,试图弄清楚这一点......我在 .NET 3.5 SP1 中使用 Entity Framework 1.0 和 ASP.NET MVC 以及 EFPocoAdapter(所以单独的 Poco 类)。

所以我有以下 Controller 之一的代码:

    [AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditUser(int? id, FormCollection form)
{
var user = new User();

using (var db = new UMSEntities { DeferredLoadingEnabled = false })
{
if (id != null)
{
user = db.Users.FirstOrDefault(p => p.UserID.Equals((int) id));
db.LoadProperty(user, p => p.UserProfiles);
db.LoadProperty(user, p => p.UserCompanyProfile);
}
else
{
user.UserGuid = Guid.NewGuid();
user.DateCreated = DateTime.Now;
user.DateLastActivity = DateTime.Now;
user.DateModified = DateTime.Now;
user.Password = "demo";
user.Version = 0;
user.SecretAnswer = "";
user.SecretQuestion = "";
user.IsApproved = true;
user.IsActive = true;

user.UserProfiles = new UserProfile();
user.UserCompanyProfile = new UserCompanyProfile
{
EmployeeID = "",
HireDate = DateTime.Now,
Title = "",
UserCode = "",
Company = db.Companies.First(p => p.CompanyID == 8)
};

db.Users.InsertOnSaveChanges(user);

}

TryUpdateModel(user);

db.SaveChanges();
}

编辑现有用户非常有效(注意 id != null)。但是,它是添加新用户的代码部分。它一直有效,直到我到达将 UserCompanyProfile 添加到用户对象的代码部分。如果我将这段代码注释掉,它就可以正常工作。当我尝试通过查询数据库将公司附加到 UserCompanyProfile 时出现问题——我收到此错误。

Entities in 'UMSEntities.UserCompanyProfiles' participate in the 'FK__UserCompa__Compa__25869641' relationship. 0 related 'Companies' were found. 1 'Companies' is expected.

顺便说一句,它实际上返回一个公司对象(它是 PocoProxies.CompanyProxy 类型)。如果有任何帮助,我们将不胜感激!

最佳答案

所以我想通了,哦,天哪,这花了我很长时间……也很明显。我没有查询公司并通过 UserCompanyProfile 关联它,而是需要以相反的方式关联它:

                // ...
user.UserProfiles = new UserProfile();
user.UserCompanyProfile = new UserCompanyProfile
{
EmployeeID = "",
HireDate = DateTime.Now,
Title = "",
UserCode = ""
};

var company = db.Companies.First(p => p.CompanyID.Equals(16));
company.UserCompanyProfile.Add(user.UserCompanyProfile);

db.Users.InsertOnSaveChanges(user);
// ...

希望这对其他人有帮助!

关于c# - Entity Framework 外键(或缺少外键),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/933052/

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