检查表中是否存在记录的最佳方法是什么。用户键入相同的名称会发生什么,我需要查看它是否在数据库中。问题是我想在使用泛型的Repository基类上进行。所以我不能去Entity.Name。
public void Save(T item)
{
Table<T> table = _db.GetTable<T>();
table.InsertOnSubmit(item);
_db.SubmitChanges();
}
这不起作用,因为项目不完全相同
if (!table.Contains(item))
{
table.InsertOnSubmit(item);
}
由于
答案 0 :(得分:0)
这将为您提供一组身份成员,您可以检查项目的主键是否包含在集合中
_db.Mapping.GetTable(T).RowType.IdentityMembers
答案 1 :(得分:0)
如果必须只使用DataContext
,则可以手动构建表达式。在这种情况下,我使用的是选择器表达式,但对属性名称(即“名称”)的反射也可以这样做:
static void Main()
{
string knownName;
using (DataClasses1DataContext ctx = new DataClasses1DataContext())
{
knownName = ctx.Customers.First().CompanyName;
}
using (DataContext ctx = new DataClasses1DataContext())
{
Console.WriteLine(ctx.Any<Customer, string>(
cust => cust.CompanyName, "none-such"));
Console.WriteLine(ctx.Any<Customer, string>(
cust => cust.CompanyName, knownName));
}
}
static bool Any<TEntity, TValue>(
this DataContext ctx,
Expression<Func<TEntity, TValue>> selector,
TValue value)
where TEntity : class
{
var lambda =
Expression.Lambda<Func<TEntity, bool>>(
Expression.Equal(
selector.Body,
Expression.Constant(value, typeof(TValue))),
selector.Parameters);
return ctx.GetTable<TEntity>().Any(lambda);
}
基于字符串的方法是:
using (DataContext ctx = new DataClasses1DataContext())
{
Console.WriteLine(ctx.Any<Customer, string>("CompanyName", "none-such"));
Console.WriteLine(ctx.Any<Customer, string>("CompanyName", knownName));
}
...
static bool Any<TEntity, TValue>(
this DataContext ctx,
string propertyOrFieldName,
TValue value)
where TEntity : class
{
var param = Expression.Parameter(typeof(TEntity), "row");
var lambda =
Expression.Lambda<Func<TEntity, bool>>(
Expression.Equal(
Expression.PropertyOrField(param, propertyOrFieldName),
Expression.Constant(value, typeof(TValue))),
param);
return ctx.GetTable<TEntity>().Any(lambda);
}