2010-08-29 101 views
0

我有一个项目的简单评级应用程序。主要有三个表:LINQ联盟列如果验证

Item 
{ 
    ItemID, 
    Contents 
} 

asp_User 
{ 
    UserID, 
    Name 
} 

Rating 
{ 
    RatingID, 
    ItemID, 
    UserID, 
    int Rating 
} 

我有LINQ代码读取项目:

var q = from item db.Item 
     select item; 

那么我想追加到包含评级的当前认证的每个项目行QA列用户。如果用户未登录或没有经过认证的用户提供评级,结果将为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}; 

回答

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. 
} 
0

从性能角度来看,Ocelots解决方案是要走的路(特别是如果您查询多个项目)。

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(); 
      } 
     } 
    } 
} 

如果你想: 但是满足这一评级应该是项目的属性的情况下,你可以用你的LINQ到SQL数据类相同的命名空间内的部分类扩展Item类要获得与Ocelot提出的单个SQL请求相同的结果,您应该使用GroupJoin(像SQL LEFT OUTER JOIN一样工作),然后像上面那样选择当前用户评级。