【问题标题】:Entity Framework Code First: One-to-Many relation (empty list)实体框架代码优先:一对多关系(空列表)
【发布时间】:2014-01-10 17:24:52
【问题描述】:

我有一个 WCF 项目,我使用实体框架 v6 和代码优先生成数据库。 但是我对 User 类和 FeedRss 之间的关系有疑问。我想为每个用户提供几个 FeedRss。我的代码工作(没有例外)但没有添加到 ICollection 提要中(在用户中),在数据库中恢复后这个列表是空的。

public class User
{
    [Key]
    public int UserID {get; set;}
    ...
    [InverseProperty("User")]
    public ICollection<FeedRSS> feeds { get; set; }

    public User()
    {
        feeds = new List<FeedRSS>();
    }
}

一个用户->多个 feedRss

public class FeedRSS
{
    [Key]
    public int ID { get; set; }
    ...
    public int UserId { get; set; }
    [ForeignKey("UserId")]
    public User User { get; set; }

    public FeedRSS()
    {
    }
 }
public class UsersContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<FeedRSS> Feeds { get; set; }
}

我的代码测试函数(但返回一个空列表):

    public User getUser(int Id)
    {
        using (UsersContext context = new UsersContext())
        {
            return context.Users.ToList().Find(
                    delegate(User u) {
                        return u.UserID == Id;
                    });
        }
    }

    public List<FeedRSS> getFeedListTest(User u)
    {
        using (UsersContext ctx = new UsersContext())
        {
            User user = ctx.Users.First(i => i.UserID == u.UserID);
            FeedRSS f = new FeedRSS() { name = "code", link = "uri" };
            user.feeds.Add(f);
            //the list user.feeds lenght is = 1
            ctx.SaveChanges();
            //update working
        }
        //get the same user in the database but the list uuu.feeds lenght is 0 :(
        User uuu = this.getUser(u.UserID);
        return uuu.feeds.ToList();
     }

我测试了其他非常不同的代码(流畅的API,在FeedRss中强制使用UserId..),但我不明白实体框架中的关系原理......我尝试了几个示例代码都不成功......

*对不起,我的英语大概是这样的

【问题讨论】:

  • 可以添加getUser方法的代码吗?我认为您必须在查询中添加一个 Include(p => p.feeds)。
  • 完成,我不知道包含。我 rtfm ^^

标签: entity-framework c#-4.0 ef-code-first code-first


【解决方案1】:

您可以按照 CodeNotFound 的建议使用 Include(...) 语句加载提要,也可以将 feeds 集合设为虚拟 - 这将启用延迟加载,EF 将自动为您加载提要。

public class User {
    ...

    [InverseProperty("User")]
    public virtual ICollection<FeedRSS> feeds { get; set; }
}

你可以在MSDN portal找到一篇关于延迟加载和急切加载的好文章

【讨论】:

  • virtual!我一直忘记它!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-05
  • 2011-07-20
  • 1970-01-01
  • 2013-03-14
  • 1970-01-01
相关资源
最近更新 更多