我有以下课程
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.类似,不同之处在于它们不是相关表中的一个值,而是相关表中可以有多个记录。如何从address表中获取这些值。
i.e. Contact.Address[0].City发布于 2014-02-19 07:12:01
下面是什么:
Contact.Addresses.FirstOrDefault().City;您的模型不完整。您必须在Address中引用Person
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; }
}发布于 2014-02-19 07:20:00
如果您能够修改模型,则访问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;https://stackoverflow.com/questions/21865442
复制相似问题