在EF中为一个对象添加值

时间:2013-04-03 20:06:41

标签: c# entity-framework

我有一个功能:

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'

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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();
    }
}