Entity Splitting with Code Only
-
21-09-2019 - |
Question
Is their a way using Entity Framework Code-Only to have an entity that has fields from two tables if both tables don't contain the primary key?
Here is an example.
public class BlogPost
{
public int PostID { get; set; }
public String PostBody { get; set; }
public int UserID { get; set; }
public string Username { get; set; }
}
public class User
{
public int UserID { get; set; }
public String Username { get; set; }
}
public class BlogPostConfiguration : EntityConfiguration<BlogPost>
{
public BlogPostConfiguration()
{
HasKey(b => b.PostID);
}
}
public class UserConfiguration : EntityConfiguration<User>
{
public UserConfiguration()
{
HasKey(b => b.UserID);
}
}
I want the Username property of the BlogPost object to be mapped to the username column of the User table. I can do the mapping using a foreign key using the designer but I'm not sure how to do that using Code Only. I tried using two MapHierarchy statements in my configuration object but it looks like that only works if both tables us the same primary key.
Solution
I don't think this is possible with the current state of Entity Framework.
In order to do entity splitting you have to have a 1-to-1 mapping (the primary key must be in both tables).
I was incorrect with my questing in assuming that because you can add columns from a second table in the designer that the code will actually work. I get a very similar error when trying to do the mapping in the EDMX as I do when using Code-Only.