【发布时间】:2012-01-03 16:49:14
【问题描述】:
MVC3 中的 EF 4.1 和延迟加载,使用代码优先模型
难以设计正确的模型。请看一下,让我知道我做错了什么。我该如何解决它。
我正在使用 Membership API 创建帐户。成功创建帐户后。我重定向以自动创建联系人记录。 contactId(自动生成数据库),userid(存储会员api生成的用户id)
模型是:
public class Contact
{
public int ContactID { set; get; }
public string UserId { set; get; }
public string LastName { set; get; }
public int? CompanyID { set; get; } // not sure if I need this as it will be NULL
public virtual Company CompanyInfo { set; get; }
}
接下来,用户可以单击创建公司链接或稍后注销并登录以创建公司记录。
public class Company
{
public int CompanyID { set; get; }
public int ContactID { set; get; }
public string CompanyName { set; get; }
public virtual Contact Contacts { set; get; }
}
当用户决定创建公司记录时,我正在检查公司是否已经存在,如果存在我只是显示联系信息和公司信息,或者如果没有找到我重定向到创建公司。
public ActionResult chckifCompanyFound()
{
int contactId = 1; //Assuming I retrieved the value
//I think I should get the data from Company table, if company data found then contact data could be retrieved using lazy loading?
Company c= db.Company.Include(c => c.Contacts).Where(x => x.ContactID == contactId).FirstOrDefault();
if(c == null)
//redirect to create company
else
// view data from c company object
}
目前,在会员 API 创建帐户后尝试创建联系人记录时,它会显示异常。我这样创建记录:
Contact contact = new Contact();
contact.UserId = userId;
contact.LastName = lastName;
db.Contacts.Add(contact);
db.SaveChanges();
例外:
无法确定类型“D.Models.Contact”和“D.Models.Company”之间关联的主体端。此关联的主体端必须使用关系流式 API 或数据注释显式配置。
非常感谢!
【问题讨论】:
标签: asp.net-mvc-3 entity-framework-4 entity-framework-4.1