Aniruddha
Aniruddha

Reputation: 1039

Entity Framework automatically inserts new row in parent table

I'm using an UI to insert data into the DB. Here is my entity model and controller. Whenever I'm inserting data into the UserDetail table, it automatically creates a new row in the UserRole table. Not sure why it's happening like this. For now UserRole is hard-coded in controller.

public class UserDetail
{
        [Key]
        public int UserID { get; set; }
        [Required]
        [StringLength(30, MinimumLength = 4)]
        public string UserName { get; set; }
        [Required]
        [StringLength(50, MinimumLength = 4)]
        public string FirstName { get; set; }
        [Required]
        [StringLength(50, MinimumLength = 4)]
        public string LastName { get; set; }
        [Required]
        [EmailAddress]
        [StringLength(150, MinimumLength = 4)]
        public string Email { get; set; }
        [Required]
        [DataType(DataType.Password)]
        [StringLength(30,MinimumLength=4)]
        public string Password { get; set; }
        public UserRole UserRole { get; set; }
}

public class UserRole
{
        [Key]
        public int RoleID { get; set; }
        [Required]
        [StringLength(20,MinimumLength=5)]
        public string RoleName { get; set; }
        public IEnumerable<UserDetail> UserDetail { get; set; }
}

[HttpPost]
public HttpResponseMessage Register(UserDetail usrInfo)
{
    UserContext ctx = new UserContext();

    UserDetail user = new UserDetail
            {
                UserRole = ctx.UserRole.Where(id => id.RoleID == 2).Select(r => r).FirstOrDefault(),
                FirstName = usrInfo.FirstName,
                LastName = usrInfo.LastName,
                UserName = usrInfo.UserName,
                Password = usrInfo.Password,
                Email = usrInfo.Email,
            };
    _unitofwork.userDetail.Add(user);

    if (_unitofwork.Completed() > 0)
        return Request.CreateResponse(HttpStatusCode.OK, "Created");
    else
        return Request.CreateResponse();
}
public class UserContext: DbContext
    {
        public UserContext():base()
        {
            Database.SetInitializer<UserContext>(new CreateDatabaseIfNotExists<UserContext>());
            //Database.SetInitializer<UserContext>(new DropCreateDatabaseIfModelChanges<UserContext>());
        }
        public DbSet<UserDetail> UserDetails { get; set; }
        public DbSet<UserRole> UserRole { get; set; }

    }

Upvotes: 0

Views: 41

Answers (1)

MikeS
MikeS

Reputation: 1764

In the statement where you are instantiating the userdetail object you use a separately defined context to query for the user role:

UserContext ctx = new UserContext();

UserDetail user = new UserDetail
        {
            **UserRole = ctx.UserRole.Where(id => id.RoleID == 2).Select(r => r).FirstOrDefault(),**
            FirstName = usrInfo.FirstName,
            LastName = usrInfo.LastName,
            UserName = usrInfo.UserName,
            Password = usrInfo.Password,
            Email = usrInfo.Email,
        };
_unitofwork.userDetail.Add(user);

if (_unitofwork.Completed() > 0)
    return Request.CreateResponse(HttpStatusCode.OK, "Created");
else
    return Request.CreateResponse()

You then add the user to the userdetail collection under the _unitofwork object which has it's own context. To make thiswork, the userrole object you retrieved has to be under the same context to which you are adding the userdetail object.

So you probably want something like:

 UserDetail user = new UserDetail
            {
                UserRole = _unitofwork.UserRole.Where(id => id.RoleID == 2).Select(r => r).FirstOrDefault(),
                FirstName = usrInfo.FirstName,
                LastName = usrInfo.LastName,
                UserName = usrInfo.UserName,
                Password = usrInfo.Password,
                Email = usrInfo.Email,
            };
    _unitofwork.userDetail.Add(user);

Upvotes: 2

Related Questions