场景:我有两个表:UserProfiles
和BlogArticles
。博客文章在UserProfile中,所以如果我想获得特定用户的所有博客文章,我会输入类似的内容:
db.UserProfiles.SingleOrDefault(x=> x.UserName == User.Idenity.Name).BlogArticles
但是,我想使用BlogArticles
表来执行此操作,也就是说,我希望获得来自同一UserProfile的BlogArticles,如下所示:
db.BlogArticles(x=> ...) // these should be from one user only.
解决方法1 一种方法是向后做,如下:
db.UserProfiles.FirstOrDefault(d => d.BlogArticles.FirstOrDefault(x=> x.Id==BlogArticles) != null);
因此,给定一个BlogArticle id,可以找到UserProfile。
但是,如何使用BlogArticle表获取来自特定用户配置文件的文章列表?
我已经尝试了
db.BlogArticles.Where(x=> Functions.GetAuthor(x.Id) == User.Identity.Name).ToList()
但是我收到以下错误:
An exception of type 'System.NotSupportedException' occurred in System.Data.Entity.dll but was not handled in user code
Additional information: LINQ to Entities does not recognize the method 'System.String GetAuthor(Int32)' method, and this method cannot be translated into a store expression.
如何以更好的方式解决这个问题?
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string Description { get; set; }
public DateTime Created { get; set; }
public virtual ICollection<BlogArtilce> BlogArticles { get; set; }
public virtual ICollection<Group> Groups { get; set; }
//public DateTime Created = DateTime.Today;
}
[Table("BlogArticle")]
public class BlogArticle
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public virtual string Name { get; set; }
public string Description { get; set; }
public virtual string Contents { get; set; }
public virtual int Views { get; set; }
public virtual string Password { get; set; }
public virtual string Tags { get; set; }
}
public class Group
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; } // this must be an int.
public string Name { get; set; }
public virtual ICollection<BlogArticle> BlogArticles { get; set; }
}
答案 0 :(得分:3)
你使这变得比它需要的复杂得多。从您的OP中您已经选择了作者,因此应该可以访问作者的ID和存储它的方法。
所以,假设BlogArticles有一个名为AuthorId的属性,你的代码可能看起来像这样:
int localAuthorId = ???; // assign from wherever you fetched it
// simpler filter:
db.BlogArticles.Where(x => x.AuthorId = localAuthorId).ToList()