سؤال

I am using ASP.Net Identity 2. I created a user as follows:

public class User : IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
    public virtual Agency Agency { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }
}

The User is a member of an Agency:

public class Agency
{

    public int Id { get; set; }

    public string Name { get; set; }

    public string TaxId { get; set; }

    public List<User> Brokers { get; set; } 
}

The User has a one to many relationship to Agency. When I am creating a user, I'll retrieve the Agency from the database and then set the Agency to the User. This is where things go awry.

            var manager = Identity.GetUserManager();
            manager.Create(new User()
            {
                UserName = "chuckconway",
                Email = "chuck@winnemen.com",
                FirstName = "Chuck",
                LastName = "Conway",
                Agency = agency

            }, "123");

Instead of referencing the Agency and inserting the primary key into the User table, ASP.NET Identity inserts a new agency record into the agency table and uses it's id with the newly created user. I end up with two agencies...

هل كانت مفيدة؟

المحلول

Normally for one-to-many relationship in EF you want to have an ID (foreign key) of the referencing table included in navigation properties, like this:

public class User : IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
  public int AgencyId { get; set; } //new
  public virtual Agency Agency { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
}

then use the AgencyId during insert/user creation, as in retrieve AgencyID from DB and assign it to User

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top