它可以工作,但是我需要验证是否已添加数据。
我在Internet上找到了以下解决方案:
public static EntityEntry<TEnt> AddIfNotExists<TEnt, TKey>(this DbSet<TEnt> dbSet, TEnt entity, Func<TEnt, TKey> predicate) where TEnt : class
{
var exists = dbSet.Any(c => predicate(entity).Equals(predicate(c)));
return exists
? null
: dbSet.Add(entity);
}
private static void AddRangeIfNotExists<TEnt, TKey>(this DbSet<TEnt> dbSet, IEnumerable<TEnt> entities, Func<TEnt, TKey> predicate) where TEnt : class
{
var entitiesExist = from ent in dbSet
where entities.Any(add => predicate(ent).Equals(predicate(add)))
select ent;
dbSet.AddRange(entities.Except(entitiesExist));
}
它对于条件简单(一次检查)的情况很好用,但是我有一个复杂的主键,并且想确定是否已经添加了使用此键的记录:
public static void Initialize(DataContext context)
{
context.Database.EnsureCreated();
context.DeviceCharacteristicModelMappings.AddIfNotExists(new DeviceCharacteristicModelMapping
{
CharacteristicId = 2,
DeviceModelId = 2
}, p => new { p.CharacteristicId, DeviceModelId });
//....
context.SaveChanges();
}
,但根本无法编译。如何正确执行?