你可以尝试:
public IEnumerable<T> InsertOrUpdate<T>(IEnumerable<T> entities, Func<T, object[]> idExpression) where T : class
and
var existingEntity = _context.Set<T>().Find(idExpression(entity));
用类似的东西调用
movie.Genres = new List<Genre>(InsertOrUpdate(movie.Genres, x => new object[] { x.Id }));
(请注意,返回一个方法IEnumerable<>
is very危险...如果你不列举它,就像
InsertOrUpdate(movie.Genres, x => x.Id);
那么该方法将不会完全执行,因为它将“按需”延迟执行)
如果只有单键表,可以将其更改为:
public IEnumerable<T> InsertOrUpdate<T>(IEnumerable<T> entities, Func<T, object> idExpression) where T : class
and
var existingEntity = _context.Set<T>().Find(new object[] { idExpression(entity) });
and
movie.Genres = new List<Genre>(InsertOrUpdate(movie.Genres, x => x.Id));