Ra3IDeN Ra3IDeN - 3 months ago 38
ASP.NET (C#) Question

How to solve error " The foreign key name was not found on the dependent type "

I have an application where I have created a login with the help of IDENTITY:

In the userTable I have created some custom properties and among these I have a property called "orgId" that lets me know which organization the user belongs to.

I created the organization Table in sql-managment studio and so far it is all good.

The orgId is a reference to the organization table (images below) and I can't figure out how to make this property a forein key on the user table.

Every time i Run the application i Get:


The foreign key name 'OrganizationId' was not found on the dependent
type


My code:

public class ApplicationUser : IdentityUser
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
[ForeignKey("OrganizationId")]
public Organizations OrgId { get; set; }

public virtual ICollection<Organizations> Organizations { get; set; }

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here

userIdentity.AddClaim(new Claim("FirstName", this.FirstName));

return userIdentity;

}
}


organizationClass:

public class Organizations
{
public long OrganizationId { get; set; }
public string OrganizationName { get; set; }

public virtual ApplicationUser User { get; set; }
}


images:

enter image description here

enter image description here

Before posting this i tried a few things and amoing them was deleting all the identity generated tables but it did not work and now I get the error above which doesn't let me create anything.

I am fairly new to identity and have probably done something wrong.

What am I missing here?

EDIT:

after @Adil Mammadov answer which is extremly helpful I keep getting other errors.

my current error:


An exception of type
'System.Data.Entity.ModelConfiguration.ModelValidationException'
occurred in mscorlib.dll but was not handled in user code

Additional information: One or more validation errors were detected
during model generation:
ApplicationUser_Organization_Source: : Multiplicity is not valid in
Role 'ApplicationUser_Organization_Source' in relationship
'ApplicationUser_Organization'. Because the Dependent Role properties
are not the key properties, the upper bound of the multiplicity of the
Dependent Role must be '*'.


aslo i thought it would be good to point out the following:
in my startup.cs I have this:

public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
createRolesandUsers();
}

private void createRolesandUsers()
{
ApplicationDbContext context = new ApplicationDbContext();

var roleManager = new RoleManager<ApplicationRole>(new RoleStore<ApplicationRole>(new ApplicationDbContext()));
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));

// In Startup iam creating first Admin Role and creating a default Admin User
if (!roleManager.RoleExists(OverWatchRoles.SuperDeveloper.ToString()))
{

// first we create Admin rool
var role = new ApplicationRole();
role.Name = "SuperDeveloper";

roleManager.Create(role);

//Here we create a Admin super user who will maintain the website

var user = new ApplicationUser();
user.UserName = "UserName";
user.Email = "myname@myemail.com";
user.FirstName = "Me";
user.LastName = "Info";
user.OrgId = 0;

string userPWD = "123MyPassWord!'#";

var chkUser = UserManager.Create(user, userPWD);

//Add default User to Role Admin
if (chkUser.Succeeded)
{
var result1 = UserManager.AddToRole(user.Id, OverWatchRoles.SuperDeveloper.ToString());
}
}

if (!roleManager.RoleExists("Developer"))
{
var role = new ApplicationRole();
role.Name = "Developer";
roleManager.Create(role);

}

if (!roleManager.RoleExists("SuperAdministrator"))
{
var role = new ApplicationRole();
role.Name = "SuperAdministrator";
roleManager.Create(role);

}

if (!roleManager.RoleExists("Administrator"))
{
var role = new ApplicationRole();
role.Name = "Administrator";
roleManager.Create(role);

}

// creating Creating Employee role
if (!roleManager.RoleExists("Employee"))
{
var role = new ApplicationRole();
role.Name = "Employee";
roleManager.Create(role);

}
}

Answer

Your models are not correct. You do not have OrganizationId in your ApplicationUser model, but you specify it as a foreign key. Also, you added two navigation properties for Organization:

// Yes, this is a navigation property
public Organizations OrgId { get; set; } 

// This is also navigation property
public virtual ICollection<Organizations> Organizations { get; set; }

Your model should look like something as below:

public class ApplicationUser : IdentityUser
{
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    [Required]    
    public long OrgId { get; set; }

    // Indicates that OrgId is foreign key for Organization navigation property
    [ForeignKey("OrgId")] 
    public virtual Organizations Organization { get; set; }

    ....
}   

public class Organizations
{
    [Key]
    public long OrganizationId { get; set; }
    public string OrganizationName { get; set; }

    public virtual ICollection<ApplicationUser> Users { get; set; }
}

Also consider changing name of Organizations class to Organization. Have a look at this example for understanding ForeignKey attribute.

Update.

This is one-to-many relationship. So, in Organization model navigation proeprty must be collection of ApplicationUser.