C# LINQ Union列(如果已验证)
我有一个简单的项目评级应用程序。有三个主要表格:C# LINQ Union列(如果已验证),c#,linq,C#,Linq,我有一个简单的项目评级应用程序。有三个主要表格: Item { ItemID, Contents } asp_User { UserID, Name } Rating { RatingID, ItemID, UserID, int Rating } 我有linq代码来读取项目: var q = from item db.Item select item; 然后,我想在q后面附加一列,其中包含当前已验证用户的每个项目行的评
Item
{
ItemID,
Contents
}
asp_User
{
UserID,
Name
}
Rating
{
RatingID,
ItemID,
UserID,
int Rating
}
我有linq代码来读取项目:
var q = from item db.Item
select item;
然后,我想在q后面附加一列,其中包含当前已验证用户的每个项目行的评级。如果用户未登录,或者认证用户未提供评级,则结果将为0
我正在使用SqlMembershipProvider,如果这很重要的话
范例
q的最终结果应该如下所示:
[已验证]
//The currently authenticated user has commented on Item.ID = 1 and has given it a 9.
q = {ID = 1, Contents = "Whatever", Rating = 9},
//The currently Authenticated user has not commented on Item.ID = 2.
{ID = 2, Contents = "Something", Rating = 0};
//There is not an authenticated user
q = {ID = 1, Contents = "Whatever", Rating = 0},
//There is not an authenticated user
{ID = 2, Contents = "Something", Rating = 0};
[未经认证]
//The currently authenticated user has commented on Item.ID = 1 and has given it a 9.
q = {ID = 1, Contents = "Whatever", Rating = 9},
//The currently Authenticated user has not commented on Item.ID = 2.
{ID = 2, Contents = "Something", Rating = 0};
//There is not an authenticated user
q = {ID = 1, Contents = "Whatever", Rating = 0},
//There is not an authenticated user
{ID = 2, Contents = "Something", Rating = 0};
您打算如何处理“var q”?很难从这个问题中看出你的意图,在这种情况下,这很重要。基于缺乏背景,以下是我能做的最好的。希望这将有助于:
if(User.IsAuthenticated)
{
var q = from item in db.Item
join r in db.Rating on c.Id equals r.ItemId
select new {ID = item.Id, Contents = item.Contents, Rating = r.Rating};
// Do whatever you want with this here.
}
else
{
var y = db.Item;
// Do whatever you want with this here.
}
从性能角度来看,解决方案是可行的(尤其是在查询多个项目时)。 但为了满足评级应该是Item属性的条件,可以通过在LINQ-to-SQL数据类的同一命名空间中使用分部类来扩展Item类:
public partial class Item
{
public int Rating
{
get
{
if (!Thread.CurrentPrincipal.Identity.IsAuthenticated)
return 0;
using (var db = new ApplicationDataContext())
{
return db.Item
.Where(r => r.ItemID == this.ItemID
&& r.UserID == Thread.CurrentPrincipal.Identity.Name)
.Select(r => r.Rating)
.SingleOrDefault();
}
}
}
}
如果您想通过像Ocelot proposed这样的单个SQL请求获得相同的结果,那么您应该使用GroupJoin(类似于SQL LEFT外部联接),并像我上面所做的那样选择当前用户评级