Entity Framework Insert object with related object

浪尽此生 提交于 2019-12-07 08:44:46

问题


I am a newbie with Entity Framework and I need to insert an object Comment that has a related FK object User into the database.

    public Class Comment
    {
        public int CommentID { get; set; }
        public string CommentContent { get; set; }
        public virtual User User { get; set; }
        public virtual DateTime CommentCreationTime { get; set; }
    }

public class User
{      

    public int UserID { get; set; }
    public string UserName { get; set; }
    public string UserPassword { get; set; }

    public string UserImageUrl{get; set;}
    public DateTime UserCreationDate { get; set; }

    public virtual List<Comment> Comments { get; set; }
}

  public void AddComment()
  {
        User user = new User() { UserID = 1 };            
        Comment comment = new Comment() { CommentContent = "This is a comment", CommentCreationTime = DateTime.Now, User = user };

        var ctx = new WallContext();
        comments = new CommentsRepository(ctx);

        comments.AddComment(comment);
        ctx.SaveChanges();
   }

Ideally, with T-SQL, if I know the PRIMARY KEY of my User object, I could just insert my Comment object and specify the PK of my 'User' in the insert statement.

I have tried to do the same with Entity Framework and it doesn't seem to work. It would be overkill to have to first fetch the User object from the database just to insert a new 'Comment'.

Please, how can I achieve this ?


回答1:


You need to attach the user object to the context so that the context knows its an existing entity

  public void AddComment()
  {
       var ctx = new WallContext();

        User user = new User() { UserID = 1 };  

        ctx.Users.Attach(user);

        Comment comment = new Comment() { CommentContent = "This is a comment", CommentCreationTime = DateTime.Now, User = user };

        comments = new CommentsRepository(ctx);

        comments.AddComment(comment);
        ctx.SaveChanges();
   }


来源:https://stackoverflow.com/questions/12617690/entity-framework-insert-object-with-related-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!