简体   繁体   中英

Entity Framework Multiple Foreign Keys on same table not mapping correctly

I have seen several examples on this site of mapping multiple foreign keys on the same table to an entity. I think I have coded things the way they are shown on the examples, but when I try to save my entity, both foreign keys are pointing to the same entity rather than two separate ones. I am expecting that my parent entity would have reference to two different entities from the linked table. My classes are as follows:

public class User: PersistentEntity
{
    [Required]
    public string FullName { get; set; }
    [Required]
    public string HID { get; set; }
    [Required]
    public string VID { get; set; }
    [Required]
    [MaxLength(100)]
    public string UserName { get; set; }

    //nav properties
    [InverseProperty("ImpersonatedUser")]
    public virtual ICollection<UserOverride> ImpersonatedUsers { get; set; }
    [InverseProperty("User")]
    public virtual ICollection<UserOverride> Users { get; set; }
}

public class UserOverride: PersistentEntity
{
    [Required]
    [ForeignKey("User")]
    public int UserId { get; set; }
    [Required]
    [ForeignKey("ImpersonatedUser")]
    public int ImpersonatedUserId { get; set; }
    [Required]
    public bool Active { get; set; }

    //nav fields
    [IgnoreForValidation]
    [ForeignKey("UserId")]
    public virtual User User { get; set; }
    [IgnoreForValidation]
    [ForeignKey("ImpersonatedUserId")]
    public virtual User ImpersonatedUser { get; set; }
} 

I create several users without any ImpersonatedUser objects on them, then try to create a new User object with one of these previous users set as the ImpersonatedUser. I am setting the ImpersonatedUserId equal to the UserId from that user and adding this entity to the list of ImpersonatedUsers on User, but when I try to save, it changes the ImpersonatedUserId to the id of the new user I am saving, and adds this same user to the list of Users on the User object. If I try to set the entire ImpersonatedUseer object and then save, I get an error about multiplicity of foreign keys not being correct.

My question is, what am I doing wrong? this looks like what I have seen as other examples out here, but I can't get it to work properly. Do I have it modeled correctly? Thanks for any help.

EDIT---

        //create a couple users
        var user = new User
        {
            FullName = "Ritchie Blackmore",
            HID = "01010101",
            VID = "rblackmore",
            UserName = "rblackmore"
        };
        var userResult = UserService.SaveOrUpdate(user);

here is how I am creating my user I am trying to save:

        var impersonatedUsers = UserService.FindByReadOnly(u => u.UserName.Equals("rblackmore"));
        var impersonatedUser = Queryable.FirstOrDefault(impersonatedUsers);


var user = new User
        {
            FullName = "Ronnie James Dio2",
            HID = "03030303",
            VID = "rjdio2",
            UserName = "rjdio2",
            Roles = new List<Role>
            {
                roleResult1.Entity,  //pre-existing role
                //TODO: the following are new roles, added while adding the user
                //probably shouldn't allow this scenario, but it might come in handy
                new Role
                {
                    Name = "Client2",
                    Description = "Client",
                    DisplayName = "Client"
                },
                new Role
                {
                    Name = "Developer2",
                    Description = "Developer",
                    DisplayName = "Developer"

                }
            },
            ImpersonatedUsers = new List<UserOverride>
            {
                new UserOverride {ImpersonatedUserId = impersonatedUser.Id, SystemId = system.Id, Active = true}
            }
        };
        var result = UserService.SaveOrUpdate(user);

As you can see, I am only setting the id of the impersonated user, not the entire impersonated user object. I have tried assigning the entire object as well, which threw an exception as it tried to change the key of the object to the new user's key.

Did you try just setting the Id and leaving the navigation properties alone? Basically, when you say:

I am setting the ImpersonatedUserId equal to the UserId from that user and adding this entity to the list of ImpersonatedUsers on User.

Leave the second part (after and) and just set the Id of User in ImpersonatedUserId property. That should create correct relationship.

Let me know how did it go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM