所以我一直在倾注这段代码,试图弄清楚这一点......我在 .NET 3.5 SP1 中使用 Entity Framework 1.0 和 ASP.NET MVC 和 EFPocoAdapter(所以单独的 Poco 类)。
所以我有以下控制器之一的代码:
[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.
顺便说一句,它实际上返回了一个 Company 对象(它的类型是 PocoProxies.CompanyProxy)。任何帮助都将不胜感激!