EF Core 2.1 - Duplicate relationships when use flu

2020-07-30 01:43发布

问题:

I develop a web API with .NET Core 2.1 and EF Core. But i have a problem with my ApplicationDbContext that i don't understand. I have 2 tables (Users and Profiles, one to many), the foreign key profile in User table is not required.

With Fluent API, when i declare my relationships, ef core create duplicate foreign key on the same reference, but why ?

Here is my userModel :

public class UserModel
{
    public long Id { get; set; }

    public string Username { get; set; }

    public string Password { get; set; }

    public DateTime DateAdded { get; set; }

    public DateTime? DateUpdated { get; set; }

    public DateTime? DateLastConnection { get; set; }

    public long? ProfileId { get; set; }

    public ProfileModel Profile { get; set; }
}

public class UserModelConfiguration : IEntityTypeConfiguration<UserModel>
{
    public void Configure(EntityTypeBuilder<UserModel> builder)
    {
        builder.ToTable("USR_USER");

        builder.Property(table => table.Id).HasColumnName("ID").HasColumnType("bigint").UseSqlServerIdentityColumn();
        builder.Property(table => table.Username).HasColumnName("USERNAME").HasColumnType("nvarchar(20)").HasMaxLength(20).IsRequired();
        builder.Property(table => table.Password).HasColumnName("PASSWD").HasColumnType("nvarchar(200)").HasMaxLength(200).IsRequired();
        builder.Property(table => table.DateAdded).HasColumnName("DATE_ADDED").HasColumnType("datetime").IsRequired().IsRequired();
        builder.Property(table => table.DateUpdated).HasColumnName("DATE_UPDATED").HasColumnType("datetime");
        builder.Property(table => table.DateLastConnection).HasColumnName("LAST_CONNECTION").HasColumnType("datetime");
        builder.Property(table => table.ProfileId).HasColumnName("PROFILE_ID").HasColumnType("bigint");

        builder.HasKey(table => table.Id);
        builder.HasAlternateKey(table => table.Username);

        builder.HasOne<ProfileModel>()
            .WithMany(p => p.Users)
            .HasForeignKey(u => u.ProfileId);
    }
}

Here is my ProfileModel :

public class ProfileModel
{
    public long Id { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }

    public ICollection<UserModel> Users { get; set; }

    public ICollection<ProfileRoleModel> ProfileRoles { get; set; }
}

public class ProfileModelConfiguration : IEntityTypeConfiguration<ProfileModel>
{
    public void Configure(EntityTypeBuilder<ProfileModel> builder)
    {
        builder.ToTable("USR_PROFILE");

        builder.Property(p => p.Id).HasColumnName("ID").HasColumnType("bigint").UseSqlServerIdentityColumn();
        builder.Property(p => p.Name).HasColumnName("PROFILE_NAME").HasColumnType("nvarchar(20)").HasMaxLength(20).IsRequired();
        builder.Property(p => p.Description).HasColumnName("PROFILE_DESCRIPTION").HasColumnType("nvarchar(200)").HasMaxLength(200).IsRequired();

        builder.HasKey(p => p.Id);
    }
}

Here is my application context :

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions options) : base(options)
    {
    }

    public DbSet<UserModel> Users { get; set; }

    public DbSet<ProfileModel> Profiles { get; set; }

    public DbSet<ProfileRoleModel> ProfileRoles { get; set; }

    public DbSet<RoleModel> Roles { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyConfiguration(new UserModelConfiguration());
        modelBuilder.ApplyConfiguration(new ProfileModelConfiguration());
        modelBuilder.ApplyConfiguration(new ProfileRoleModelConfiguration());
        modelBuilder.ApplyConfiguration(new RoleModelConfiguration());
    }
}

And the migrations result, as you can see, there is two foreign keys. Because of that, when i query my DbSet User i have an sql error 'Unknown column ProfileId1'

CREATE TABLE [USR_PROFILE] (
    [ID] bigint NOT NULL IDENTITY,
    [PROFILE_NAME] nvarchar(20) NOT NULL,
    [PROFILE_DESCRIPTION] nvarchar(200) NOT NULL,
    CONSTRAINT [PK_USR_PROFILE] PRIMARY KEY ([ID])
);

GO

CREATE TABLE [USR_USER] (
             [ID] bigint NOT NULL IDENTITY,
             [USERNAME] nvarchar(20) NOT NULL,
             [PASSWD] nvarchar(200) NOT NULL,
             [DATE_ADDED] datetime NOT NULL,
             [DATE_UPDATED] datetime NULL,
             [LAST_CONNECTION] datetime NULL,
             [PROFILE_ID] bigint NULL,
             [ProfileId1] bigint NULL,
             CONSTRAINT [PK_USR_USER] PRIMARY KEY ([ID]),
             CONSTRAINT [AK_USR_USER_USERNAME] UNIQUE ([USERNAME]),
             CONSTRAINT [FK_USR_USER_USR_PROFILE_PROFILE_ID] FOREIGN KEY ([PROFILE_ID]) REFERENCES [USR_PROFILE] ([ID]) ON DELETE NO ACTION,
             CONSTRAINT [FK_USR_USER_USR_PROFILE_ProfileId1] FOREIGN KEY ([ProfileId1]) REFERENCES [USR_PROFILE] ([ID]) ON DELETE NO ACTION
    );

    GO

Same problem with my other DbSet but i think it's a similar problem.

I have based my configuration on this documentation Fully Defined Relationship

回答1:

It's because you have navigation property

public ProfileModel Profile { get; set; }

but in fluent configuration

builder.HasOne<ProfileModel>()

you are telling EF that it's not a part of that relationship. Hence EF conventionally maps it to another separate relationship with automatically generated FK name.

You should always use the Has / With method overloads which represent the presence/absence of a navigation property at the corresponding end of the relationship.

In your case, replace the above with

builder.HasOne(u => u.Profile)

and the problem will be solved.