简体   繁体   中英

EF 6.1.3 and child property

I have this mvc controller:

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);
}

Everything works, but I just want the Customer.Country.Code to have a value. And since this one lists for all customers with the same country...

Same for when I use a raw SqlQuery (because of the geolocation stuff)

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();

I have the countryid in the customer object, because that is the Foreign Key. And have seen some extension method which you could use to include other data. But according to my intellisens, it's not availble. Probably something easy. But too hard for a friday afternoon (for me).

In order to use the Include() extension method you need to add the following:

using System.Data.Entity;

See DbExtensions.Include

Example usage:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM