设置1到多的正确方法所以我可以使用Entity Framework 6在Included表上查询属性

问题描述 投票:1回答:1

我目前有一个2表设置。我可以轻松地包含Associated表,但我希望能够在Where子句中使用条件,并且不确定我需要在哪里更改它。这种关系是一个人可以拥有多个地址

    public partial class People
{
  public People()
    {
        Address = new HashSet<Address>();
    }

    public int Id { get; set; }
    public int Name { get; set; }

    public virtual ICollection<Address> Address { get; set; }
}
public partial class Address
{
    public int id { get; set; }

    public string State { get; set; }


    public int PeopleId { get; set; }
    public People People { get; set; }

}

我现在可以这样做,它包括关联数据,但这会返回比我需要的更多的数据。

 using (DBContextdb = new DBContext())
        {

            var oooo = db.People.IncludeOptimized(x => x.Address).ToListAsync();
        }

我想在这些方面做点什么,但我需要正确设置我的关系。这实际上不允许我在Address类中选择State的属性。

 using (DBContext db = new DBContext())
        {

            var oooo = db.People.IncludeOptimized(x => x.Address).Where(x => x.Address.State == "Florida").ToListAsync();
        }
c# entity-framework-6
1个回答
0
投票

您无法访问'state'属性,因为'x.Address'是一个集合。 State-Property的类型是int?。但是你试着将它与字符串“Florida”进行比较。所以你也应该改变它。因此,如果您需要具有状态'佛罗里达'的所有地址,您可以使用以下内容:

简化的Model类:

    public class Model1
    {
       public IQueryable<People> People { get; set; }
       public IQueryable<Address> Addresses { get; set; }

       public Model1()
       {
           People = new List<People>().AsQueryable() ;
           Addresses = new List<Address>().AsQueryable();
       }
   }

新的地址/人员类:

public partial class People
{
    public People()
    {
        Address = new HashSet<Address>();
    }

    public int Id { get; set; }
    public int Name { get; set; }

    public virtual ICollection<Address> Address { get; set; }
}
public partial class Address
{
    public int Id { get; set; }

    public string State { get; set; }


    public int PeopleId { get; set; }
    public People People { get; set; }

}

然后您可以使用以下代码:

Model1 model = new Model1();
var queryResult = model.Addresses.Where(a => a.State == "Florida");

编辑这是您要查找的查询:

IQueryable<People> queryResult = model.Addresses.Where(a => a.State == "Florida").Select(a => a.People);
© www.soinside.com 2019 - 2024. All rights reserved.