开发者

In EF Code-first can three entities share the same connecting table?

Given the following situation, Entity Framework Code-first missnames/renames the connecting or Join table.

public class User () {
 //all fields from Users table
 //...
 //Role collection from Roles table through UserRoleLinks table
 public List<Role> Roles { get; set; }
} 

public class AppUser() {
 //subset of fields from Users through AppUsers View
 //...
 //Role collection from Roles table through UserRoleLinks table
 public开发者_StackOverflow List<Role> Roles { get; set; }
}

Both User and AppUser have the following config entry:

this.HasMany(e => e.Roles)
    .WithMany().Map(m => {
        m.MapLeftKey(a => a.Id, "Users_Id");
        m.MapRightKey(b => b.Id, "Roles_Id");
        m.ToTable("UserRoleLinks");
});

At runtime I get the following error when trying to use the AppUsers (DbSet<AppUser>).

"Invalid object name 'dbo.UserRoleLinks1'." "Invalid object name 'dbo.UserRoleLinks1'."

It appears that the Code-first configuration is incrementing the Join table name because one already exists.

How can I get this working? Is there a better way to get a subset of a table's columns?


I think this is not possible in EF at all (not only in code-first). Until you prove that this is possible in EDMX there is no reason to try it in code-first.

The problem here is that AppUser is new entity for EF. Now you have M:N relation between the User <-> Roles and AppUser <-> Roles and you want to map both M:N relations into the same junction table. Because EF doesn't see that AppUser is actually only View/Query on top of User table it will probably mark this as invalid mapping.

If you only use AppUser to get subset of columns use projection into custom type in linq query instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜