I have 3 entities:
Foo
Bar
UniqueFooBar
Foo
and Bar
are entities as follows:
public class Bar {
public int Id {get; set;}
// inverse nav property
public virtual UniqueFooBar UniqueFooBar {get; set;}
}
public class Foo {
public string Name {get; set;}
// inverse nav property
public virtual UniqueFooBar UniqueFooBar {get; set;}
}
And UniqueFooBar
is a lookup as follows:
public class UniqueFooBar {
public string FooName {get; set;}
public int BarId {get; set;}
// nav properties
public virtual Foo Foo {get; set;}
public virtual Bar Bar {get; set;}
}
With constraints that:
Foo
is unique- there is a one-to-one relationship to both
Foo
andBar
Foo
Name is the PKThe fluent API is as follows:
class UniqueFooBarConfiguration : EntityTypeConfiguration<UniqueFooBar> { public UniqueFooBarConfiguration() { // Define the tablename and schema Map(entity => entity.ToTable("UniqueFooBars")); //// Define non-conventional key HasKey(fooBar => fooBar.FooName); // Define FKs - 1-to-1 HasRequired(fooBar => fooBar.Foo) .WithRequiredPrincipal(foo => foo.UniqueFooBar) .Map(key => key.MapKey("FooName")); HasRequired(fooBar => fooBar.Bar) .WithRequiredPrincipal(bar => bar.UniqueFooBar) .Map(key => key.MapKey("BarId")); // -------------------------------- } }
What is happening is that FooName
is being added to the Foo table and BarId
is being added tot he Bar table.
If, in the fluent API configuration for UniqueFooBar
, I instead try to use Foo's "Name" property then there is an error that the field already exists. Same happens if I try to use Bar's "Id" property.
How can I configure UniqueFooBar to have FKs to Foo.Name
and Bar.Id
as one-to-one relationships?
Update
- Neither
Foo
norBar
has constraint or requirement of aUniqueFooBar
. - A UniqueFooBar record requires a
FooName
and aBarId
This does not appear to be the same as How to declare one to one relationship using Entity Framework 4 Code First (POCO)