从两个相关模型类获取数据的问题

时间:2012-07-25 19:10:11

标签: c# entity-framework entity-framework-4.1

我有桌子:

Items{ItemId, Title, CreatedBy, CreatedOnDate}
Likes{ItemId, UserId, CreatedOnDate}

如果我有这两个模型:

[Table("Likes")]
    public class Like
    {
        [Key, Column(Order = 1)]
        public int ItemId { get; set; }
        [Key, Column(Order = 2)]
        public Guid UserId{ get; set; }
        public DateTime CreatedOnDate { get; set; }

        public virtual Item Item { get; set; }
        public virtual User User { get; set; }
    }
[Table("Items")]
public class Item
    {
        [Key]
        public int ItemId { get; set; }
        public virtual ICollection<Like> Likes { get; set; }
    }

现在我无法获得用户喜欢的列表。我尝试过以下方法:

model = (from l in con.Likes
                       select new Item
                                  {
                                      UserId = l.Item.UserId,
                                      Title = l.Item.Title,                                      
                                      Likes = l.Item.Likes,
                                      User = l.Items.User,                                      
                                      CreatedOnDate = l.Ticket.CreatedOnDate,
                                      ItemId = l.Ticket.ItemId
                                  }).ToList();

我尝试使用和不使用ToList()。我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

  

...获取用户喜欢的项目列表......

读这篇文章我建议:

var query = from l in con.Likes
            where l.User.UserId == givenUserId
            select l.Item;
var result = query.ToList();

但是这远离你自己的查询,我觉得你想要别的东西。