私はエンティティフレームワークを使用し、一連のユーザーを持っています:
public class DbModel : DbContext
{
public DbSet<User> Users { get; set; }
次のようにユーザーを追加します。
User UserOne = new User();
model.Users.Add( UserOne );
ユーザー数をリクエストします: int userCount = model.Users.Count();
userCount は「0」です。「1」が必要です。DetectChanges を追加しても役に立ちません。「model.SaveChanges()」の後、Count = 1 ですが、それは遅すぎて、検証のためにメモリ内のものと DB のものを組み合わせる必要があります。これを行う方法はありますか?
解決
Erik Philips の回答を使用して、DbSet の次の拡張メソッドを作成しました。
public static class DBSetExtentions
{
public static IEnumerable<T> AllMembers<T>(
this DbSet<T> target,
Func<T, bool> selection
) where T : class
{
return target.Local.Where(selection).Union(target.Where(selection));
}
}
次のようなすべてのエンティティで選択と検証を行うことができます。
private void ValidateEmail(ValidationDto validationDto)
{
int usersWithSameEmail =
validationDto.Model.Users.AllMembers(
x => x.EmailAddress.Equals( EmailAddress ) ).Count();
if (usersWithSameEmail > 1)
{
validationDto.Result.Add(new ValidationResult("Email address is in use"));
}
}