相关类/表(一对多)的正确代码优先EF6结构

时间:2014-02-18 21:14:08

标签: c# linq entity-framework

我有以下课程

public class Person
{
    [Key]
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public virtual ICollection<Address> Addresses { get; set; }
}

public class Address
{
    public int Id { get; set; }
    public string City{ get; set; }
    public string State{get; set;} 
}

我的问题类似于this previous question.,除了它们不是相关表中的一个值,相关表中可以有多个记录。如何从地址表中获取值。

i.e. Contact.Address[0].City

2 个答案:

答案 0 :(得分:0)

怎么样:

Contact.Addresses.FirstOrDefault().City;

您的模型不完整。您必须在Person中引用Address

public class Person
{
    [Key]
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual ICollection<Address> Addresses { get; set; }
}

public class Address
{
    [Key]
    public int Id { get; set; }
    public string City { get; set; }
    public string State { get; set; }

    public virtual Person Person { get; set; }
}

答案 1 :(得分:0)

如果您能够修改模型,访问Address(通过Person)的一种方法是定义关系。假设存在某种形式的数据访问,请考虑更改地址的定义,如下所示。

public virtual List<Address> Addresses {get;set;} // implementing the collection of addresses
public int AddressId {get;set;} // this is the foreign key 

然后您可以访问地址列表,如此...

 //YourDbContext is System.Data.Entity.DbContext
 List<Address> listOfAddresses = (from listOfPersons in YourDbContext.Persons.Include(listOPersons.Addresses)
 .Where(p=>p.Id==ParameterValue).FirstOrDefault()).Addresses;
 string city = listOfAddresses[0].City;