1

I am working with the fluent api to setup the relationships for my entity database. I have the typical AspNetUsers table, this table has a column called Id (String) which is the primary key for the table. I extended IdentityUser and gave it other properties, 2 such properties are AdvisorProfile, and StudentProfile.

ApplicationUser has optional AdvisorProfile and StudentProfile. AdvsiorProfile and StudentProfile have required Account (ApplicationUser).

My problem, when the tables generate AdvisorProfile has a property called Account_Id, which is the link back to ApplicationUser in AspNetUser's table. I want to change that naming convention but my fluent api code doesn't seem to be making a difference.

Fluent Api for Account -> Advisor / Account foreign key naming

//Advisor Profile to Login Account
modelBuilder.Entity<ApplicationUser>().HasOptional(x => x.AdvisorProfile).WithRequired(x => x.Account).Map(x => x.MapKey("AdvisorFK"));
modelBuilder.Entity<ApplicationUser>().HasOptional(x => x.AdvisorProfile).WithRequired(x => x.Account).WillCascadeOnDelete(false);

modelBuilder.Entity<Advisor>().HasRequired<ApplicationUser>(x => x.Account).WithOptional(x => x.AdvisorProfile).Map(x => x.MapKey("AccountFK"));
modelBuilder.Entity<Advisor>().HasRequired<ApplicationUser>(x => x.Account).WithOptional(x => x.AdvisorProfile).WillCascadeOnDelete(false);

Table Generation Code:

CreateTable(
    "dbo.Advisors",
    c => new
        {
            Id = c.Long(nullable: false, identity: true),
            FirsName = c.String(),
            LastName = c.String(),
            MiddleName = c.String(),
            Email = c.String(),
            PhoneNumber = c.String(),
            PrimaryContact = c.Int(nullable: false),
            Account_Id = c.String(nullable: false, maxLength: 128),
                    })
                .PrimaryKey(t => t.Id)
                .ForeignKey("dbo.AspNetUsers", t => t.Account_Id) //Here is the issue
                .Index(t => t.Account_Id);

1 Answer 1

2

The problem is that you use multiple fluent configurations for one and the same relationship, which is error prone and hard to say which one actually applies.

As a rule of thumb, always use single fluent mapping per relationship. In your case, it should be something like this:

//Advisor Profile to Login Account
modelBuilder.Entity<ApplicationUser>()
    .HasOptional(x => x.AdvisorProfile)             
    .WithRequired(x => x.Account)
    .Map(x => x.MapKey("AdvisorFK"))
    .WillCascadeOnDelete(false);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.