2011-04-26 84 views
1

我有一个稍微模糊的模型,用户来自Active Directory,但从此信息从SQL数据库到达。使用实体框架的属性数据库查找(计数)

所以,我有一个UserRepository,目前允许用户从活动目录搜索其他用户 - 这将返回一个列表,我绑定到一个网格。

我需要能够检查每个用户是否有任何联系人(它们居住在数据库中),以便更改UI的行为方式。

你会如何做到这一点?在另一页上联系人将是可编辑的,但在列表中,我只需要知道是否有任何联系人。我没有看到任何干净的方式来发出一个数据库调用为每个结果执行存储过程来获取计数,我得到的是计数而不是联系人列表,以尽可能简化它。

我想上线的东西:

/// <summary> 
/// information resides in the database 
/// </summary> 
private int? contactsCount = null; 
public int ContactsCount 
{ 
    get 
    { 
    if (!contactsCount.HasValue) 
     throw new ApplicationException("Error trying to access property ContactsCount before it has been initialised. The underlying repository code needs to handle the retrieval of this info."); 
    return contactsCount.Value; 
    } 
    set { contactsCount = value; } 
} 

,并使用UserRepository寻找每一行后设置ContactsCount的值(使用标准的SQL连接),但是这将是很好的将看到实体框架在实际属性上的作用,但我不确定如果主用户对象不是实体模型的一部分,我只能将一个属性绑定到函数上?

回答

0

它不可能直接与实体框架。我认为这是一个非常适合你已经拥有的专用UserRepository类。

作为一个方面说明,我会尽力避免每个用户一个单独的数据库调用,而不是你可以用一个单一的查询,像这样的事情解决了这个[警告:未经测试的代码进取]:

var users = GetUsersFromActiveDirectory(); 


// get the nof contacts per user fill in the contacts count for each user 
// assuming a IsContactFrom property on Contact here, which corresponds to User.UserName 
// also, assuming the number of users this is called for is 'reasonable' 
using (db = new MyObjectContext()) 
{ 
    var userNames = users.Select(u => u.UserName).ToList(); 

    var usersWithContacts = from c in db.Contacts 
          where userNames.Contains(c.IsContactFrom) 
          group by c.IsContactFrom into ContactsPerUser 
          select new 
          { 
           UserName = c.IsContactFrom, 
           NofContacts = ContactsPerUser.Count() 
          }; 

    var dic = usersWithContacts.ToDictionary(u => u.UserName); 

    foreach (var u in users) 
    { 
     u.ContactsCount = usersWithContacts[u.UserName].Count 
    } 




} 
0

我不太确定你在做什么。如果你有一个联系表,被称为登录栏,然后你可以运行沿着这些路线

var qry = from c in ctx.Contacts 
    group c by c.Login 
    into grp 
    select new 
    { 
     Login = grp.Key, 
     Count = grp.Count() 
    }; 

假设你有IEnumerable<User> users,保持用户的列表,从Active Directory中的东西,然后你可以做到这一点合并结果:

var dictionary = qry.ToDictionary(x => x.Login); 
users.Foreach(x=> x.ContactsCount = dictionary.ContainsKey(x.Login) ? dictionary[x.Login].Count : 0); 

这里假设你已经在你的用户类,其中的foreach这样定义(即我发现自己使用相当频繁的扩展方法)定义ContactsCount属性:

public static void Foreach<T>(this IEnumerable<T> enumerable, Action<T> action) 
{ 
    foreach (T value in enumerable) 
    { 
     action(value); 
    } 
}