We need to define a One-To-One relationship between following entities:
public class Foo
{
[Key, Column("Foo_ID")]
public int Id { get; set; }
public Bar Bar { get; set; }
}
public class Bar
{
[Key, Column("Bar_ID")]
public int Id { get; set; }
[Column("Bar_Foo_ID")]
public int? FooId { get; set; }
public Foo Foo { get; set; }
}
We need to migrate a legacy software and have both of them running side by side for now. So we can't change any relations. Unfortunately there are no foreign keys defined in the database.
modelBuilder.Entity<Foo>()
.HasOptional(a => a.Bar)
.WithRequired(x => x.Foo)
.WillCascadeOnDelete(true);
When we query Foo
and Include(x => x.Bar)
it creates a SQL query with LEFT OUTER JOIN bars ON Foo_ID = Bar_ID
which is wrong.
We need to change this to a LEFT OUTER JOIN bars on Foo_ID = Bar_Foo_ID
, but I'm not sure how Entity Framework supports that as we don't have foreign keys in our DB and Bar_ID
as PrimaryKey.
I know that there can be potentially more than one Bars
for one Foo
, but is there a way to enforce a One-To-One relationship?
When a Foo
is created, a Bar
is always created for it.