I have this:
public class Foo
{
public int Id { get; set; }
public Bar Bar { get; set; }
}
public class Bar
{
public int Something { get; set; }
public int SomethingElse { get; set; }
}
and my database is like this:
CREATE TABLE [Foo](
[Id] INT,
[Bar_Something] INT NOT NULL,
[Bar_SomethingElse] INT NOT NULL,
)
When I get the DB context with
public class DB: DbContext
{
public DbSet<Foo> Foo { get; set; }
}
Foo.Id
is mapped correctly but Bar
cannot be mapped with this error System.InvalidOperationException : The entity type 'Bar' requires a primary key to be defined.
I don't want to create Bar table and give its id as FK to Foo.
How can I map the columns Bar_Something
and Bar_SomethingElse
to Foo.Bar.Something
and Foo.Bar.SomethingElse
?
EF Core 2.0 and later support Owned entity types. By default, those are mapped using Table splitting.
In EF Core 2.1, you probably only need to add the [Owned]
attribute to Bar
, ie :
[Owned]
public class Bar
{
public int Something { get; set; }
public int SomethingElse { get; set; }
}
The owned type's properties will be mapped to fields in the same table named Property_OwnedProperty
. In this case it will be Bar_Something
and Bar_SomethingElse
Looks like someone designed the table with those requirements in mind.
In EF Core 2.0 you need to specify the owned type in the context configuration :
modelBuilder.Entity<Foo>().OwnsOne(p => p.Bar);
a primary key to be defined in your Bar class.
public class Bar
{
[Key]
public int Something { get; set; }
public int SomethingElse { get; set; }
}