0

我有一个功能:

public void Add(User user)            
{
    var id = WebSecurity.CurrentUserId;
    //add id to FK CUserID 
    context.User.Add(user); 
}

我正在将用户数据添加到数据库。如何将 id 值添加到 CUserID?

public class User
{
    [key]    
    public int UserID { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public string E-mail { get; set; }

    public UserProfile CUserID { get; set; }

}

public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int CUserId { get; set; }
    public string UserName { get; set; }
}

编辑:如果我尝试这样做:

user.CUserId = id;

我收到一个错误:

无法将类型“int”隐式转换为“Project.Models.UserProfile”

4

2 回答 2

0

继续你在问题中描述的内容,试试这个:

public void Add(User user)
{
    using (var context = new MyDbContext())
    {
        var currentUser = context.UserProfile.Single(
            u => u.UserName == System.Web.HttpContext.Current.User.Identity.Name);

        var newUser = new User();
        newUser.Name = user.Name;
        newUser.Surname = user.Surname;
        newUser.Email = user.Email;
        newUser.CUserID = currentUser.CUserId;

        context.User.Add(newUser);
        context.SaveChanges();
    }
}
于 2013-04-03T23:02:14.703 回答
0

更改User班级:

public class User
{
    [key]    
    int UserID { get; set; }
    string Name { get; set; }
    string Surname { get; set; }
    string E-mail { get; set; }

    [ForeignKey("UserProfile)]
    int CUserID { get; set; }
    virtual UserProfile UserProfile { get; set; ]
}

现在您可以设置值和实体框架将在您保存更改时ID获得匹配。UserProfile

于 2013-04-03T20:50:11.110 回答