且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实体框架 - 命名“自动生成” InverseProperty表

更新时间:2023-09-23 23:25:28

答案也在回答中更新



如Ladislav Mrnka的回答,流利的API是解决方案。我删除了[InverseProperty]属性,并将创建的关系添加到DataContext类。

  protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{
modelBuilder.Entity< Event>()
.HasMany(e => e.InvitedEvents)
.WithMany(u => u.InvitedUsers)
.Map(mc =>
{
mc.ToTable(%TABLENAME%);
mc.MapLeftKey(UniqueId);
mc.MapRightKey( UniqueId);
});
}


I did a bit of searching but can't find a same problem / question. I have a question regarding the table naming (in the database) when EF creates a table encountering InverseProperty DataAnnotation

"Dummy/Demo code" :

public class User
{
    public Guid Id { get; set; }
    public String Name { get; set; }

    public virtual List<Event> InvitedEvents { get; set;}
    public virtual List<Event> AcceptedEvents { get; set;}
    public virtual List<Event> DeclinedEvents { get; set;}
}

public class Event
{
    public String Name { get; set;}

   [InverseProperty("InvitedEvents")]
   public virtual List<User> InvitedUsers { get; set; }
   [InverseProperty("AcceptedEvents")]
   public virtual List<User> AcceptedUsers { get; set; }
   [InverseProperty("DeclinedEvents")]
   public virtual List<User> DeclinedUsers { get; set; }

}

This all works and the lookup tables is created, but my question is How can i give that table a name ?

They are now named (something like) - EventUser - EventUser_1 - EventUser_2

I want to give some more "readable" names to it.

Hope it's clear.

UPDATE!

As answered by Ladislav Mrnka, fluent API was the solution. I removed the [InverseProperty] properties and added the creation of relations to the DataContext class.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Event>()
        .HasMany(e => e.InvitedEvents )
        .WithMany(u => u.InvitedUsers )
        .Map(mc =>
            {
                mc.ToTable("%TABLENAME%");
                mc.MapLeftKey("UniqueId");
                mc.MapRightKey("UniqueId");
             });
}

You need to make sure that each class contains a UniqueId column (in my demo example EventId, UserId)

The answer also updated in answer

As answered by Ladislav Mrnka, fluent API was the solution. I removed the [InverseProperty] properties and added the creation of relations to the DataContext class.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Event>()
        .HasMany(e => e.InvitedEvents )
        .WithMany(u => u.InvitedUsers )
        .Map(mc =>
            {
                mc.ToTable("%TABLENAME%");
                mc.MapLeftKey("UniqueId");
                mc.MapRightKey("UniqueId");
             });
}