Question

I'm attempting to create a many-to-many mapping between User and Group models. Here are my classes:

public abstract class Entity
{
    public Guid Id { get; set; }
    public DateTime Created { get; set; }
    public DateTime? Modified { get; set; }
}

public class User : Entity
{
    public string Email { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Group> Groups { get; set; }
}

public class Group : Entity
{
    public string Name { get; set; }
    public virtual ICollection<User> Users { get; set; }
}

As you can see, I'm using the Entity abstract class to implement common properties in the classes that inherit from it. In this case, Id will be the key property for all of my EF classes.

Here is my configuration file where I map the many-to-many relationship:

public GroupConfiguration()
{
    Property(x => x.Id).IsRequired().HasDatabaseGeneratedOption(databaseGeneratedOption: DatabaseGeneratedOption.Identity);
    Property(x => x.Name).HasMaxLength(50).IsRequired();

    HasMany(g => g.Users)
        .WithMany(u => u.Groups)
        .Map(m =>
        {
            m.MapLeftKey("Id");
            m.MapRightKey("Id");
            m.ToTable("UserGroups");
        });
}

When I attempt to add a migration, I get the following error: Id: Name: Each property name in a type must be unique. Property name 'Id' is already defined. It seemingly doesn't like the fact that the property being mapped on both sides has the same identifier. When I don't inherit from Entity for one of the classes, eg. User, and make the mapping property UserId it is able to successfully create a migration.

Is there any way around this? It would be to be able to use an Id property for all of my entities defined in an abstract class.

Thanks in advance.

Était-ce utile?

La solution

You can't have 2 keys with the same name, it will represent the columns for your relationship table (named "UserGroups"). When you call "MapLeftKey" or "MapRightKey", you define the columns name.

So I suggest you to rename your Ids (UserId and GroupId for example) and your mapping should be alright. I think you cannot have another solution on using fluent API.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top