Search code examples
c#-4.0ef-code-firstentity-framework-4.1entity-framework-5table-per-type

EF 5.0 table-per-type inheritance gives strange queries


I have standard table-per-type inheritance case in code first approach to an existing schema:

[Table("base_object")]
public partial class BaseObject
{
  public BaseObject()
  { 

  }

  [Key]
  [Column("id")]
  public long Id {get; set;}
  [Column("slug")]
  public string Slug {get; set;}
  ...       
}

[Table("user")]
public partial class User: BaseObject
{
  public User()
  {

  }

  [Column("login")]
  public string Login {get; set;}
  [Column("email")]
  public string Email {get; set;}
}

Mapping is straightforward as described in annotations, user.id is primary key and foreign key to base_object.id

In test case, during first call to "Users" repository from Context, EF is generating query:

SELECT 
1 AS [C1], 
'0X0X' AS [C2], 
[Extent1].[id] AS [id], 
[Extent2].[slug] AS [slug], 
[Extent1].[login] AS [login], 
[Extent1].[email] AS [email], 
[Extent1].[BaseObject_id] AS [BaseObject_id]
FROM  [dbo].[user] AS [Extent1]
INNER JOIN [dbo].[base_object] AS [Extent2] ON [Extent1].[id] = [Extent2].[id]

which gives an error, because column "user.BaseObject_id" does not exists! Whitout this line: *[Extent1].[BaseObject_id] AS [BaseObject_id]* query would be OK.

What am I doing wrong?

I am using EF5.0 with .NET 4.0


Solution

  • It turned out that "..." made the difference.

    BaseObject had a collection:

    [InverseProperty("Object")]
    public virtual ICollection<UserHasObjectRight> UserHasObjectRights { get; set; }
    

    And User had a collection:

    [InverseProperty("User")]
    public virtual ICollection<UserHasObjectRight> UserHasObjectRights { get; set; }
    

    It was causing a strange query generation. I have to remove duplicating collection from base object class and it started to work.