EF Code First和linq扩展方法 - 外键,我做错了吗?

时间:2012-08-19 22:37:06

标签: linq entity-framework key

我有这样的事情:(伪代码)

public class Author
{
   int id;
   public List<Thread> Threads;
   public List<ThreadPoints> ThreadPointses;
}

public class Thread
{
   int id;
   public List<ThreadPoints> ThreadPointses;
}

public class ThreadPoints
{
   int id;
   int Points;
}

我不确定以上是否正确,但现在我想获得点数&#39;指定的Author在指定的Thread中有。 我无法直接调用ThreadPoints.Thread_id,因为它无法访问,即使它实际上在数据库中也是如此。 那么我需要改变我的模型,还是我不知道一些有用的方法?


基本上,我的模型看起来像这样:

    public class Account
    {
        [Key]
        public Guid AccountId { get; set; }
        public string UserName { get; set; }
        public List<Post> Posts { get; set; }
        public List<Post> ModifiedPosts { get; set; }
        public List<Thread> Threads { get; set; }
        public List<ThreadPoints> ThreadPointses { get; set; }
        public List<Thread> LastReplied { get; set; }
        public int Points { get; set; }
    }

    public class Thread
    {
        [Key]
        public int Id { get; set; }
        public List<ThreadPoints> ThreadPointses { get; set; } 
        public List<Post> Posts { get; set; }
        public int CurrentValue { get; set; }
        public int NumberOfPosts { get; set; }
        public int TotalValue { get; set; }
        public int Views { get; set; }
        public string Title { get; set; }
        public DateTime DateCreated { get; set; }
    }

    public class ThreadPoints
    {
        [Key]
        public int Id { get; set; }
        public int Points { get; set; }
    }

我需要的是,当用户创建一个帖子时,他会给它一些点数。在下一个操作中,我想获取该数量的点(来自数据库),并增加它。但我只有线程ID作为输入信息。

你的答案可能很好,(至于我试图实现它),但无论如何,我不确定这个模型。也许我应该手动将外键添加到我的模型中?它肯定会更简单,但是我的数据库中会有两个外键......

1 个答案:

答案 0 :(得分:2)

由于你没有明确地映射你的FK,实体框架正在生成它们并将它们隐藏起来,所以要获得属性的Id,你需要遵循导航集。

我不确定您的问题,但是您想要给定作者的特定PointsThreadpoint的数量吗?你的模型似乎不太支持这个,但你可以做这样的事情 -

public int GetPoints(Author author, Thread thread)

    {
      int points = author.Threads.FirstOrDefault(t => t.id == thread.id).ThreadPointses.Sum(tp => tp.Points);
    }

这将返回包含在线程点列表中的所有点的总和,这些点包含在与传入的线程具有相同ID的线程列表中,用于指定的作者。

如果这对您不起作用 - 您可以发布您的实际模型吗?