简体   繁体   English

实体框架自动在父表中插入新行

[英]Entity Framework automatically inserts new row in parent table

I'm using an UI to insert data into the DB. 我正在使用UI将数据插入数据库。 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. 每当我将数据插入UserDetail表时,它都会在UserRole表中自动创建新行。 Not sure why it's happening like this. 不知道为什么会这样发生。 For now UserRole is hard-coded in controller. 目前, UserRole已在控制器中进行了硬编码。

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; }

    }

In the statement where you are instantiating the userdetail object you use a separately defined context to query for the user role: 在实例化userdetail对象的语句中,使用单独定义的上下文来查询用户角色:

UserContext ctx = new UserContext(); 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. 然后,将用户添加到具有自己上下文的_unitofwork对象下的userdetail集合中。 To make thiswork, the userrole object you retrieved has to be under the same context to which you are adding the userdetail object. 为了完成这项工作,您检索到的userrole对象必须处于与要添加userdetail对象相同的上下文中。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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