使用延迟加载的MVC3中的EF 4.1

时间:2011-12-19 23:19:13

标签: asp.net-mvc-3 entity-framework-4

使用代码优先模型

在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.UserId = userId;
   contact.LastName = lastName;
   db.Contacts.Add(接触);
   db.SaveChanges();

  

例外:
   无法确定类型'D.Models.Contact'和'D.Models.Company'之间关联的主要结束。必须使用关系流畅API或数据注释显式配置此关联的主要结尾。

非常感谢你!

3 个答案:

答案 0 :(得分:1)

尝试:

 Contact cc = db.Contacts.Include(c=>c.CompanyInfo).Where(x => x.ContactID == product.ContactID).FirstOrDefault();

答案 1 :(得分:1)

尝试以下(来自this link):

Contact cc = db.Contacts.Include( "CompanyInfo" ).Where(x => x.ContactID == product.ContactID).FirstOrDefault();

答案 2 :(得分:1)

尝试用以下代码替换模型:

public class Contact
{
   public int ContactId { set; get; }
   public string UserId { set; get; }
   public int CompanyId { get; set; }
   public string LastName { set; get; }
   public virtual Company Company { set; get; }
}

public class Company
{    
  public int CompanyId { set; get; }
  public string CompanyName { set; get; }
  public virtual ICollection<Contact> Contacts { set; get; }
}

您的Contact需要一个CompanyId,因为它只有一个与之相关的公司,它将作为该联系人与公司之间的外键。导航属性CompanyInfo将用于延迟加载。您的Company对象只需要Contacts集合,因为Contact是在数据库中创建关系的位置。

要回答有关查询的问题,我需要更多信息......产品在哪里播放?我没有从联系人或公司那里看到它,但如果您想要联系公司,请执行以下操作:

var company = dbContext.Contacts.Find(userId).Company;
Console.WriteLine("Company Name: {0}", company.CompanyName);
相关问题