steventnorris
steventnorris

Reputation: 5896

Dotnet Entity Framework Include without a Foreign Key

I have two models:

Location

Facility

Location's FacilityMnemonic can be null. It's possible that the location may have a facility mnemonic that does not have a facility. I need a way to structure these entities so that I can do some form of

_context.Locations.Where(CONDITIONS HERE).Include("Facility").ToList();

And then be able to package that up in a nice json response for my web API. I cannot use a foreign key, however, because the constraint will fail if there is a mnemonic with no matching facility. Having trouble determining the right way to do this with entity framework. Any guidance appreciated.

Upvotes: 0

Views: 1272

Answers (1)

Asherguru
Asherguru

Reputation: 1741

You cannot use include without relationship in SQL server.

You can use this instead

var list = (from a in _context.Location.Where(CONDITIONS HERE) 
            from b in _context.Facility.Where(CONDITIONS HERE related to Location).DefaultOrEmpty()
            select new Location() {
                Id = a.Id,
                Name = a.Name,
                Facilities = b
            }).ToList();

Upvotes: 2

Related Questions