Entity Framework でオブジェクトが変更監視中かどうか調べる方法メモ

DbSet<TEntity>.Local プロパティを調べればわかった。

public class Customer
{
    // Entity Framework 用コンストラクタ
    protected Customer()
    {
    }

    public Customer(string name)
    {
        Name = name;
    }

    public int Id { get; private set; }

    public string Name { get; private set; }
}

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext()
        : base("DefaultConnection") {}

    public ApplicationDbContext(string nameOrConnectionString)
        : base(nameOrConnectionString) {}

    private DbSet<Customer> _customers;

    public DbSet<Customer> Customers => _customers ?? (_customers = Set<Customer>());
}

public class CustomerRepository
{
    private ApplicationDbContext _dbContext = new ApplicationDbContext();

    public void Store(Customer customer)
    {
        if (0 < customer.Id)
        {
            _dbContext.Customers.Add(customer);
        }
        else
        {
            // 変更監視中でなければ監視下にする
            if (_dbContext.Customers.Local.Contains(customer) == false)
            {
                _dbContext.Entry(customer).State = EntityState.Modified;
            }
        }
        _dbContext.SaveChanges();
    }
}