@Yalçın Mete, Welcome to Microsoft Q&A, after checking the source code of the two methods, I find they are almost the same.
DbContext.Add Source Code:
public virtual EntityEntry Add(object entity)
{
CheckDisposed();
return SetEntityState(Check.NotNull(entity, nameof(entity)), EntityState.Added);
}
DbSet.Add Source Code
public override EntityEntry<TEntity> Add(TEntity entity)
{
var entry = EntryWithoutDetectChanges(entity);
SetEntityState(entry.GetInfrastructure(), EntityState.Added);
return entry;
}
They both used SetEntityState
method to add the data.
However, there are some notes you need to care.
DbContext.Add can be handy when you have multiple entity types to add and you want to manage them all within the same context.
DbSet.Add is often used when you're working directly with a particular entity set within the context.
In most scenarios, you'll find yourself using DbSet.Add()
because it's more convenient and specific, especially when you're working with a particular type of entity. However, there might be cases where using DbContext.Add()
could be more appropriate, such as when you're dealing with multiple entity types within the same context. Ultimately, both methods achieve the same goal of adding entities to the context, so the choice between them depends on the specific requirements of your application and the context in which you're working.
Hope it could help you.
Best Regards,
Jack
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.