问题
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)
回答1:
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");
});
}
来源:https://stackoverflow.com/questions/14135501/entity-framework-naming-a-autogenerated-table-on-inverseproperty