我要寻找一种方式来创建普通GetById这让 params对象[]
作为参数,知道找到钥匙/ s的场/秒和了解,找到相关实体。
I am looking a way to create Generic GetById that get params object[]
as parameter, knows to find the key/s field/s and know to find the relevant entity.
在寻求解决方案我想在返回的PK场的定义,并且可以返回基于域的实体泛型方法泛型方法的方式。
In the way to find a solution I thought on a generic method that returns the PK fields definition and a generic method that can return the entity based on fields.
我要寻找的东西,我可以在表中使用的一个或多个字段作为主键。
I am looking for something I can use in table with one or more fields as primary key.
修改 一个或多个字段作为主键为例= Customers表有(CompanyId,客户名称,地址,CREATEDATE)。 客户的主键是CompanyId的客户名称。
EDIT one or more fields as primary key example = table Customers have (CompanyId, CustomerName, Address, CreateDate). The primary key of Customers are CompanyId are CustomerName.
我要寻找通用GetById将知道还可以处理表格的这种。
I am looking for generic GetById that will know to handle also those such of tables.
您不能获得通用的方法,如果你不知道有多少成员是在关键的和什么类型的他们有。我修改my对于单个键多个密钥,但你可以看到它的解决方案是不通用的 - 它使用顺序按键定义:
You can't get "generic" approach if you don't know how many members is in the key and what types do they have. I modified my solution for single key to multiple keys but as you can see it is not generic - it uses order in which keys are defined:
// Base repository class for entity with any complex key
public abstract class RepositoryBase<TEntity> where TEntity : class
{
private readonly string _entitySetName;
private readonly string[] _keyNames;
protected ObjectContext Context { get; private set; }
protected ObjectSet<TEntity> ObjectSet { get; private set; }
protected RepositoryBase(ObjectContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
Context = context;
ObjectSet = context.CreateObjectSet<TEntity>();
// Get entity set for current entity type
var entitySet = ObjectSet.EntitySet;
// Build full name of entity set for current entity type
_entitySetName = context.DefaultContainerName + "." + entitySet.Name;
// Get name of the entity's key properties
_keyNames = entitySet.ElementType.KeyMembers.Select(k => k.Name).ToArray();
}
public virtual TEntity GetByKey(params object[] keys)
{
if (keys.Length != _keyNames.Length)
{
throw new ArgumentException("Invalid number of key members");
}
// Merge key names and values by its order in array
var keyPairs = _keyNames.Zip(keys, (keyName, keyValue) =>
new KeyValuePair<string, object>(keyName, keyValue));
// Build entity key
var entityKey = new EntityKey(_entitySetName, keyPairs);
// Query first current state manager and if entity is not found query database!!!
return (TEntity)Context.GetObjectByKey(entityKey);
}
// Rest of repository implementation
}