【问题标题】:UWP Sqlite one-to-many relationUWP Sqlite 一对多关系
【发布时间】:2016-10-04 12:15:39
【问题描述】:

我正在尝试将 SQLite 与新的 EF Core 一起使用,并且一直在关注 tutorial。在我也使用 SQLite 之前,我使用了一个额外的 DB 类,并引用了真实的类。例如下面Blog_DB 包含IDBlogImage(另一个类),然后我用来创建真正的Blog 类,将BlogImage 类加载到Blog.BlogImage

public class Blog_DB
{
public int BlogId { get; set; }
public string Url { get; set; }

public int BlogImageID { get; set; }
}

public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }

public BlogImage BlogImage { get; set; }
}

public class BlogImage
{
    public int BlogImageId { get; set; }
    public byte[] Image { get; set; }
    public string Caption { get; set; }
}

但是现在我听说了 EF Core,它是 one-to-oneone-to-many 关系,通过以下方式完成:

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public BlogImage BlogImage { get; set; }
}

public class BlogImage
{
    public int BlogImageId { get; set; }
    public byte[] Image { get; set; }
    public string Caption { get; set; }

    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

但我不明白,这是如何工作的(或者我没有正确理解/阅读文档),因为当我加载 Blogs 时,条目 BlogImage 是空的。

using (var db = new BloggingContext())
{
    var m = db.Blogs.FirstOrDefault(); // the first entry
    m.BlogImage = new BlogImage { Caption = "My Caption" }; // does not work
    db.BlogImage.Add(new BlogImage { Blog = m, BlogId = m.BlogId, Caption = "My Caption" }); // doesn't work either
    db.SaveChanges();                
}

【问题讨论】:

    标签: c# database entity-framework sqlite uwp


    【解决方案1】:

    当我加载博客时,条目 BlogImage 为空。

    在实体框架中,一个实体可以通过关联(relationship)与其他实体相关联。而Navigation properties 提供了一种导航两种实体类型之间关联的方法,并且通过使用 Include 方法来加载相关的导航属性。由于 EF Core 的官方文档不完整,这里是关于 EF6.x 的 Loading Related Entities 的文档。

    在这种情况下,实体 BlogImage 是实体 Blog 的导航属性。所以使用db.BlogImage.Add(new BlogImage { Blog = m, BlogId = m.BlogId, Caption = "My Caption" }); 添加BlogImage 确实有效,但是您应该使用Include 方法为Blog 加载实体BlogImage。

    以下是我验证过的代码:

    using (var db = new BloggingContext())
    {
        // load the Blog without BlogImage
        var blogWithoutBlogImage = db.Blogs.FirstOrDefault();//blogWithoutBlogImage.BlogImage is null
    
        // load the Blog inclue the BlogImage
        var blogWithBlogImage = db.Blogs.Include(x => x.BlogImage).FirstOrDefault();
        var blogImage = blogWithBlogImage.BlogImage;
    }
    

    【讨论】:

    • 谢谢,这正是我想要的,Include 部分成功了
    猜你喜欢
    • 2017-07-12
    • 2015-11-11
    • 2014-01-29
    • 2015-02-14
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    相关资源
    最近更新 更多