I have three distinct well-defined entities, Foo
, Bar
, Baz
, on one side of the relationship, and a single entity these all need to be tied to on the other side, lets call it LogEntry
. I have the relationship working as far as sql is concerned, but I'm at a loss at how to define it within the DbContext
modelBuilder
and get the navigation props to work both directions when loading from the db using .Include()
.
Requirements:
LogEntry
must be related to exactly oneFoo
,Bar
, orBaz
Foo
,Bar
, orBaz
may only be related to zero or oneLogEntry
s
Desired usage:
I'd like to have a navigation property both ways.
.Include(x => x.LogEntry)...
when retrieving all Foo
, Bar
, or Baz
s
and
db.LogEntries.Include(x => x.Foo).Include(x => x.Bar).Include(x => x.Baz)...
What I've tried:
We're using code-first, but we generate the tables from .sql
scripts.
--LogEntry.sql rough details
LogEntry UNIQUEIDENTIFIER NONCLUSTERED PRIMARY KEY NOT NULL,
FooID UNIQUEIDENTIFIER NULL
BarID UNIQUEIDENTIFIER NULL
BazID UNIQUEIDENTIFIER NULL
-- Other Fields, etc...
-- CONSTRAINT FKs to the Foo,Bar,Baz tables
-- CONSTRAINT CHECK (FooID IS NOT NULL AND BarID IS NULL AND BazID IS NULL or ...etc)
-- to make sure each LogEntry is related to one entity regardless of type
-- CONSTRAINT UNIQUE for each Foo, Bar, Baz ID that isn't null
I've tried a few different ways to define the relationship with the DbContext
ModelBuilder
, but nothing I've tried populates the nav prop when .Include()
ed.
// Example
modelBuilder.Entity<Foo>
.HasOptional(f => f.LogEntry)
.WithRequired(l => l.Foo);
The first approach was to put a nullable FK on each Foo
, Bar
, or Baz
and have Lists of Foo
, Bar
, or Baz
nav props on LogEntry
. We would just rely on code to never add more than one Foo
, Bar
, or Baz
to a LogEntry
. This made the entity relationship trivial, but it didn't match how they were going to be used and would lead to dev confusion. The other issue being we can't implement a unique check on the LogEntry
FKs across Foo
, Bar
, or Baz
tables.
In summary:
Is there a way to define this relationship in entity framework to get working navigation properties for both sides?