gpt4 book ai didi

c#-4.0 - Entity Framework 插入对象与相关对象

转载 作者:行者123 更新时间:2023-12-04 23:05:48 24 4
gpt4 key购买 nike

我是 Entity Framework 的新手,我需要插入一个对象 Comment具有相关 FK 对象 User进入数据库。

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

理想情况下,使用 T-SQL,如果我知道我的 User 的 PRIMARY KEY |对象,我可以插入我的 Comment对象并在插入语句中指定我的“用户”的 PK。

我试图对 Entity Framework 做同样的事情,但它似乎不起作用。必须首先获取 User 是多余的对象只是为了插入一个新的“评论”。

请问,我怎样才能做到这一点?

最佳答案

您需要将用户对象附加到上下文,以便上下文知道其现有实体

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

关于c#-4.0 - Entity Framework 插入对象与相关对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12617690/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com