C# 显示特定用户的所有博客文章

C# 显示特定用户的所有博客文章,c#,.net,asp.net-mvc,performance,asp.net-mvc-4,C#,.net,Asp.net Mvc,Performance,Asp.net Mvc 4,场景:我有两个表:UserProfiles和BlogArticles。博客文章在UserProfile中,因此如果我想获取特定用户的所有博客文章,我会键入如下内容: db.UserProfiles.SingleOrDefault(x=> x.UserName == User.Idenity.Name).BlogArticles 但是,我希望使用blogracts表来实现这一点,也就是说,我希望获得来自相同用户配置文件的blogracts,如下所示: db.BlogArticles(x=&

场景:我有两个表:
UserProfiles
BlogArticles
。博客文章在UserProfile中,因此如果我想获取特定用户的所有博客文章,我会键入如下内容:

db.UserProfiles.SingleOrDefault(x=> x.UserName == User.Idenity.Name).BlogArticles
但是,我希望使用
blogracts
表来实现这一点,也就是说,我希望获得来自相同用户配置文件的blogracts,如下所示:

db.BlogArticles(x=> ...) // these should be from one user only.
db.UserProfiles.FirstOrDefault(d => d.BlogArticles.FirstOrDefault(x=> x.Id==BlogArticles) != null); 
解决方案1 一种方法是向后执行,如下所示:

db.BlogArticles(x=> ...) // these should be from one user only.
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.
我怎样才能更好地解决这个问题


[表(“用户配置文件”)]
公共类用户配置文件
{
[关键]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId{get;set;}
公共字符串用户名{get;set;}
公共字符串电子邮件{get;set;}
公共字符串说明{get;set;}
已创建公共日期时间{get;set;}
公共虚拟ICollection博客文章{get;set;}
公共虚拟ICollection组{get;set;}
//public DateTime Created=DateTime.Today;
}
[表(“博客文章”)]
公共类博客文章
{
[关键]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
公共int Id{get;set;}
公共虚拟字符串名称{get;set;}
公共字符串说明{get;set;}
公共虚拟字符串内容{get;set;}
公共虚拟int视图{get;set;}
公共虚拟字符串密码{get;set;}
公共虚拟字符串标记{get;set;}
}
公共课组
{
[关键]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id{get;set;}//这必须是一个int。
公共字符串名称{get;set;}
公共虚拟ICollection博客文章{get;set;}
}

你让事情变得比需要的复杂得多。您已经从OP中选择了一位作者,因此应该可以访问该作者的id以及存储该id的方法

因此,假设BlogArticles有一个名为AuthorId的属性,那么您的代码可能看起来像这样:

int localAuthorId = ???; // assign from wherever you fetched it

// simpler filter:
db.BlogArticles.Where(x => x.AuthorId = localAuthorId).ToList()

你能显示UserProfile和BlogArticle的类吗?他们有PK FK吗relation@EhsanSajjad,请查看我的最新编辑。@artem:您没有包含BlogArticle类。@Ehsan Sajjad,现在已修复@Artem始终发布回答问题所需的完整详细信息,假设所有id都正确映射到模型中。你不必这样做,然后你就“被困”在了导航属性上。@Maarten:我假设在作者和文章之间存在单向引用,这是因为作者包含了一系列文章。我还假设Article类可以引用父级/作者,因为这是解决OP问题的唯一方法。事实证明没有这样的属性。而且该模型不适合以OP尝试的方式解决这个问题,因为所有文章都在作者之间分开的桶中。谢谢你的回答!