The DbSet<TEntity>.Add method returns an entity. I would normally have expected an Add
operation to have a void
return type.
When I look at the EntityFramework source code, I see the following implementation:
public virtual TEntity Add(TEntity entity)
{
Check.NotNull(entity, "entity");
GetInternalSetWithCheck("Add").Add(entity);
return entity;
}
GetInternalSetWithCheck
returns an InternalSet<TEntity>
The Add
method of InternalSet<TEntity>
interestingly enough has a void return type in its signature:
public virtual void Add(object entity)
My concern is whether or not I need to be careful with when I do modifications to an entity with relation to when it is added to a DbSet.
E.g. are there cases where
var entity = new MyEntity();
_dbSet.Add(entity);
entity.SomeDatModifyingMethod();
_dbContext.SaveChanges();
might give different behavior than
var entity = new MyEntity();
entity.SomeDatModifyingMethod();
_dbSet.Add(entity);
_dbContext.SaveChanges();
or different behavior than:
var entity = new MyEntity();
entity = _dbSet.Add(entity);
entity.SomeDatModifyingMethod();
_dbContext.SaveChanges();
In the basic default implementation, it wouldn't ever matter, because it just always returns exactly the same instance. However, the Add
method is virtual
, so it can be overridden (though in the public source code, the only override is a test double - but I'm not sure that source code actually includes e.g. the SqlServer support implementation).
Why does DbSet Add return an entity instance instead of void?
A DbSet represents the collection of all entities in the context, or that can be queried from the database, of a given type. DbSet objects are created from a DbContext using the DbContext. Set method.
This can be achieved in several ways: setting the EntityState for the entity explicitly; using the DbContext. Update method (which is new in EF Core); using the DbContext. Attach method and then "walking the object graph" to set the state of individual properties within the graph explicitly.
Entity types can be mapped to database views using the Fluent API. EF will assume that the referenced view already exists in the database, it will not create it automatically in a migration. C# Copy. modelBuilder.
DbContext generally represents a database connection and a set of tables. DbSet is used to represent a table. Your code sample doesn't fit the expected pattern.
It allows you to write a "Find or Add" pattern
var person = context.People.Find(ssn) ?? context.People.Add(new Person
{
SocialSecurityNumber = ssn,
FirstName = "John",
LastName = "Doe"
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With