gpt4 book ai didi

ef-code-first - Entity Framework 5 - 代码优先数组导航属性一对多与接口(interface)类型

转载 作者:行者123 更新时间:2023-12-04 03:44:10 25 4
gpt4 key购买 nike

这些是我的课:

public class Post : IPost
{
public int Id { get; set; }
public virtual int[] DuplicateOf { get; set; }
public virtual ICommentInfo[] Comments { get; set; }
}

public class CommentInfo : ICommentInfo
{
public virtual string Author { get; set; }
public virtual int Id { get; set; }
public virtual string Text { get; set; }

public virtual int PostId{ get; set; }
[ForeignKey("PostId")]
public virtual Post Post { get; set; }
}

将此 CommentConfiguration 添加到 OnModelCreate() 中:
HasRequired(c => c.Post)
.WithMany(b=>(ICollection<CommentInfo>) b.Comments)
.HasForeignKey(b=>b.PostId)
.WillCascadeOnDelete(true);

我真的不明白为什么属性 Comments 总是为空,以及为什么 EF 不初始化它,因为它是虚拟的。
我也尝试禁用延迟加载,但是当我尝试使用 context.Post.Include("Comments") 加载导航属性时一个错误告诉我“没有名为评论的导航属性”。
所以我尝试使用Entity Framework Power Tools Beta 3来查看实体数据模型,我发现即使两个表之间存在关系并且也有Comment表端,表“Post”也没有导航端。

我真的不知道该转向哪个方向,可能是阵列的问题?我应该使用 Icollection 属性吗?
虽然我无法更改该属性的类型,因为 Post 正在实现一个接口(interface)。

我看到的每个样本都清晰且易于制作。请帮助我..提前谢谢你。

编辑:

这是我在查看 link 后所做的更改我昨天发的。
  public class Post : IPost
{
public int Id { get; set; }
public virtual int[] DuplicateOf { get; set; }
public virtual ICollection<CommentInfo> Comments { get; set; }
ICommentInfo[] IPost.Comments {
get { return Comments ; }
set { Comments = (CommentInfo[])value; } }
}

异常(exception)是: System.ObjectDisposedException :The ObjectContext instance has been disposed and can no longer be used for operations that require a connection并在应用程序尝试获取评论时引发。
如果我删除 virtual键异常消失,但属性始终为空,并且值不会以任何方式持续存在。

EDITv2
我已经解决了添加新属性并将旧属性映射到它的问题。
public class Post : IPost
{
public int Id { get; set; }
public virtual int[] DuplicateOf { get; set; }
public ICommentInfo[] Comments
{
get { return ListComments.ToArray(); }

}
public List<CommentInfo> ListComments {get;set;}
}

在我的 PostConfiguration OnModelCreate() 中,我使用 ListComments 属性作为导航属性,如下所示:
HasMany(b => b.ListComments)
.WithRequired(c=>c.Post)
.HasForeignKey(c=>c.PostId)
.WillCascadeOnDelete(true);

现在它完美地工作了,它比我预期的要简单,当我尝试接收评论集合时,如果我包含“ListComments”属性,我会得到 Post 数组。
感谢您的帮助!

最佳答案

我无法访问您评论中的链接,但我认为您已更改

public virtual ICommentInfo[] Comments { get; set; }

进入定义导航属性的常用方法:
public virtual ICollection<CommentInfo> Comments { get; set; }

因为 Entity Framework 在其概念模型中不支持接口(interface)。

已释放上下文的异常意味着您在获取 Post 后访问该属性。来自数据库的对象并处理上下文。这会在与数据库的连接丢失时触发延迟加载。解决方案是使用 Include :
var posts = context.Posts.Include(p => p.Comments).Where(...)

现在可以一次性获取帖子和评论。

关于ef-code-first - Entity Framework 5 - 代码优先数组导航属性一对多与接口(interface)类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14790960/

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