EF Doesn't Like Same Named Tables
Posted
by Anthony Trudeau
on Geeks with Blogs
See other posts from Geeks with Blogs
or by Anthony Trudeau
Published on Tue, 02 Jul 2013 14:17:34 GMT
Indexed on
2013/07/03
5:06 UTC
Read the original article
Hit count: 203
.NET
Originally posted on: http://geekswithblogs.net/tonyt/archive/2013/07/02/153327.aspx
It's another week and another restriction imposed by the Entity Framework (EF). Don't get me wrong. I like EF, but I don't like how it restricts you in different ways. At this point you may be asking yourself the question: how can you have more than one table with the same name?
The answer is to have tables in different schemas. I do this to partition the data based on the area of concern. It allows security to be assigned conveniently. A lot of people don't use schemas. I love them. But this article isn't about schemas.
In the situation I have two tables:
- Contact.Person
- Employee.Person
The first contains the basic, more public information such as the name. The second contains mostly HR specific information. I then mapped these tables to two classes. I stuck to a Table per Class (TPC) mapping, because of problems I've had in the past implementing inheritance with EF. The following code gives you the basic contents of the classes.
[Table("Person", Schema = "Employee")]
public class Employee {
...
public int PersonId { get; set; }
[ForeignKey("PersonId")]
public virtual Person Person { get; set; }
}
[Table("Person", Schema = "Contact")]
public class Person {
[Key]
public int Id { get; set; }
...
}
This seemingly simple scenario just doesn't work. The problem occurs when you try to add a Person to the DbContext. You get an InvalidOperationException with the following text:
The entity types 'Employee' and 'Person' cannot share table 'People' because they are not in the same type hierarchy or do not have a valid one to one foreign key relationship with matching primary keys between them..
This is interesting for a couple of reasons. First, there is no People table in my database. Second, I have used the SetInitializer method to stop a database from being created, so it shouldn't be thinking about new tables.
The solution to my problem was to change the name of my Employee.Person table. I decided to name it Employee.Employee. It's not ideal, but it gets me past the EF limitation. I hope that this article will help someone else that has the same problem.
© Geeks with Blogs or respective owner