我有以下一些代码,并希望将它添加到keyvaluepair列表/数组/字典中,哪个最好。
一点背景: 目前,这个片段直接与数据库进行交互,它在一个循环内部,在每次迭代生成数据时都会推送到数据库。我的总体意图是将这些数据推送到列表/字典等,以便我可以立即将所有数据推送到DB。这是:
_dataContext.GetRepository<UserRole, Guid>().Insert(new[]
{
new UserRole
{
Id = Guid.NewGuid(),
UserId = newGroup.CreatedById,
RoleId = SecurityConstants.RoleId.GROUP_ADMINISTRATOR,
GroupId = newGroup.Id,
CreatedById = newGroup.CreatedById
},
new UserRole
{
Id = Guid.NewGuid(),
RoleId = SecurityConstants.RoleId.CONTACT_PERSON,
UserId = newGroup.CreatedById,
GroupId = newGroup.Id,
CreatedById = newGroup.CreatedById
}
});
上面的GetRepository然后如上所述访问数据库。我想以任何方式单独存储数据,以便稍后将其推送到数据库
public interface IMydDataContext : IDisposable
{
IRepository<TEntity, TKrey> GetRepository<TEntity, TKrey>() where TEntity : class, IDomainObject<TKrey>;
IDbSet<TEntity> Set<TEntity, TKey>() where TEntity : class, IDomainObject<TKey>;
int SaveChanges();
Task<int> SaveChangesAsync();
}
我在这里声明字典:
Dictionary<UserRole, Guid> _usersRepositoryDictionary = new Dictionary<UserRole, Guid>();
并尝试以这种方式将数据放入其中:
_usersRepositoryDictionary.Add(new[] { new UserRole
{
Id = Guid.NewGuid(),
UserId = newGroup.CreatedById,
RoleId = SecurityConstants.RoleId.GROUP_ADMINISTRATOR,
GroupId = newGroup.Id,
CreatedById = newGroup.CreatedById
},
new UserRole
{
Id = Guid.NewGuid(),
RoleId = SecurityConstants.RoleId.CONTACT_PERSON,
UserId = newGroup.CreatedById,
GroupId = newGroup.Id,
CreatedById = newGroup.CreatedById
}
});
然而,我在&#34;添加&#34;那说,&#34;没有任何论据符合所要求的形式参数&#39;值&#39; of Dictionary.Add(UserRole,Guid)&#34;
任何线索我做错了什么?
答案 0 :(得分:1)
您可以像这样定义字典:
Dictionary<UserRole, Guid> _usersRepositoryDictionary = new Dictionary<UserRole, Guid>();
你加入它就像这样:
_usersRepositoryDictionary.Add(new[] { new UserRole
{
Id = Guid.NewGuid(),
UserId = newGroup.CreatedById,
RoleId = SecurityConstants.RoleId.GROUP_ADMINISTRATOR,
GroupId = newGroup.Id,
CreatedById = newGroup.CreatedById
},
new UserRole
{
Id = Guid.NewGuid(),
RoleId = SecurityConstants.RoleId.CONTACT_PERSON,
UserId = newGroup.CreatedById,
GroupId = newGroup.Id,
CreatedById = newGroup.CreatedById
}
});
您应该添加 dict.Add(新UserRole [] {...}),然后添加 dict.Add(UserRole,Guid);
你需要这样的东西:
var userRole = new UserRole
{
Id = Guid.NewGuid(),
UserId = newGroup.CreatedById,
RoleId = SecurityConstants.RoleId.GROUP_ADMINISTRATOR,
GroupId = newGroup.Id,
CreatedById = newGroup.CreatedById
};
_usersRepositoryDictionary.Add(userRole, userRole.Id);
现在可以很清楚,Id信息几乎是多余的,所以我建议更好地抽象你的数据模型(例如继承具有Id属性的IEntity的东西)。