代码之家  ›  专栏  ›  技术社区  ›  JP Hellemons

EF 6.1.3和儿童财产

  •  0
  • JP Hellemons  · 技术社区  · 7 年前

    我有一个mvc控制器:

    public ActionResult Index(string country)
    {
        var c = _hc.Countries.Where(l => l.Code.Equals(country, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
        var customers = _hc.Customers.Where(h => h.Country.Code.Equals(country, StringComparison.InvariantCultureIgnoreCase));
    
        foreach (var h in customers)
            h.Country = c;
    
        return View(customers);
    }
    

    一切正常,但我只想 Customer.Country.Code 要有价值。因为这张表列出的是同一个国家的所有客户。。。

    当我使用生的 SqlQuery

    var customers = _hc.Database.SqlQuery<Customer>(@"
                    SELECT customers.*, countries.code
                    FROM [dbo].customers
                    inner join countries on customers.countryid = countries.id
                    where geography::Point(50.436912, 5.972050, 4326).STDistance(geography::Point([Latitude], [Longitude], 4326)) <= 25000").ToList();
    

    我在customer对象中有countryid,因为这是外键。我们已经看到了一些扩展方法,可以用来包含其他数据。但根据我的情报,这是不可用的。可能很简单。但是对于一个星期五下午来说太难了(对我来说)。

    1 回复  |  直到 7 年前
        1
  •  0
  •   SpruceMoose    7 年前

    为了使用Include()扩展方法,需要添加以下内容:

    using System.Data.Entity;
    

    看见 DbExtensions.Include

    var customers = _hc.Customers
        .Include(h => h.Country)
        .Where(h => h.Country.Code.Equals(country, StringComparison.InvariantCultureIgnoreCase));