首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >相关类/表的适当代码优先EF6结构(一对多)

相关类/表的适当代码优先EF6结构(一对多)
EN

Stack Overflow用户
提问于 2014-02-19 05:14:08
回答 2查看 324关注 0票数 0

我有以下课程

代码语言:javascript
复制
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表中获取这些值。

代码语言:javascript
复制
i.e. Contact.Address[0].City
EN

回答 2

Stack Overflow用户

发布于 2014-02-19 07:12:01

下面是什么:

代码语言:javascript
复制
Contact.Addresses.FirstOrDefault().City;

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

代码语言:javascript
复制
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; }
}
票数 0
EN

Stack Overflow用户

发布于 2014-02-19 07:20:00

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

代码语言:javascript
复制
public virtual List<Address> Addresses {get;set;} // implementing the collection of addresses
public int AddressId {get;set;} // this is the foreign key 

然后您可以访问地址列表,如下所示...

代码语言:javascript
复制
 //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;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21865442

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档