Is it possible to create a dynamic query with Entity Framework. I Have 18 tables, Each of them has the same structures. How can I create a dynamic query to reuse the same query for each tables. I would like to have a generic query for Create Read Update Delete.
The read contains the same "Where" Clause.
Thanks for your help.
Here you have simple example for pure CRUD scenario. Create interface which will contain shared properties for your queries. Implement this interface in all your entity classes. Than create repository. Repository is usually defined as generic but in your case I defined each method as generic so that you can use same repository instence for all entities.
public interface IWellKnownEntity
{
int Type { get; set; }
}
public class Repository
{
public T GetEntityByWellKnownQuery<T>() where T : IWellKnownEntity
{
using (var context = new MyContext())
{
return context.CreateObjectSet<T>().FirstOrDefault(e => e.Type == 1);
}
}
public IEnumerable<T> GetEntitiesByCustomQuery<T>(Expression<Func<T, bool>> where)
{
using (var context = new MyContext())
{
return context.CreateObjectSet<T>().Where(where).ToList();
}
}
public void Create<T>(T entity) where T : IWellKnownEntity
{
using (var context = new MyContext())
{
context.AddObject(entity);
context.SaveChanges();
}
}
public void Update<T>(T entity) where T : IWellKnownEntity
{
using (var context = new MyContext())
{
context.Attach(entity);
context.ObjectStateManager.ChageObjecState(entity, EntityState.Modified);
context.SaveChanges();
}
}
public void Delete<T>(T entity) where T : IWellKnownEntity
{
using (var context = new MyContext())
{
context.Attach(entity);
context.DeleteObject(entity);
context.SaveChanges();
}
}
}
Than you suppose that you have entity product and catebory which impelment well known interface. You can simply call:
var repository = new Repository();
var product = repository.GetEntityByWellKnownQuery<Product>();
product.Name = "Updated";
repository.Update<Product>(product);
var category = repository.GetEntitiesByCustomQuery<Category>(c => c.Id == 1).First();
repository.Delete<Category>(category);
You can futher improve the sample code. This code doesn't use shared context so it is more usable for disconnected scenario (web application). If you use connected scenario like WinForms application or batch application you can implement IDisposable on repository and share context among all methods. Dispose method on repository will hanlde disposing of context. Code for Update and Delete methods will be different because there is no need to attach entity back to context or set entity state.
Related
I have a many-to-many relationship between Entity A and Entity B. Entity Framework has automatically created a junction table in SQL Server after running the migration. (I don't have this junction table defined anywhere in the code.) For example:
class EntityA
{
// ...
public ICollection<EntityB> Foo { get; set; }
}
class EntityB
{
// ...
public ICollection<EntityA> Bar { get; set; }
}
I need to replace the Foo collection on EntityA using a (detached) list coming in from a client application. I've spent the better part of a day trying to figure this out. Here is what I've tried:
[HttpPut]
public async Task<IActionResult> Update(EntityA someEntity)
{
var entry = context.EntityA.Attach(someEntity);
entry.State = EntityState.Modified;
var collection = entry.Collection(x => x.Foo);
collection.IsModified = true;
await context.SaveChangesAsync();
}
I've also tried changing the CurrentValue property of collection, and obviously I've also tried replacing Foo directly, but nothing seems to work -- the junction table remains empty. How can this child list be entirely replaced without having to Include() / load the entire list into memory for manual tracking / removal?
Ivan (in the comments above) is right. After some trial and error, I ended up writing an extension method that works for my case. Before I get to that, I want to credit this answer for pointing me in the right direction, which I ended up modifying to get it working with auto-generated EF junction tables. First, the extension method:
// assuming your models inherit from a base class or implement an interface
public interface IEntity
{
Guid Id { get; set; } // or int or whatever your ID field is
}
public static class DbExtensions
{
// Updates the many-to-many child collections of an entity (for an auto-generated EF junction table)
public static async Task UpdateJunctionTableAsync<T, Y>(this DbContext baseContext, T entity, Expression<Func<T, IEnumerable<Y>>> property)
where T : class, IEntity
where Y : class, IEntity
{
// scope these calls to a new context -- working off the base context
// tends to cause issues down the line with the change tracking
using var context = new DbContext();
// EF internally compares with DB entities, so we'll do the same
var dbEntity = await context.FindAsync<T>(entity.Id);
var dbEntry = context.Entry(dbEntity);
// access the collection entry that resulted in a junction table
var dbItemsEntry = dbEntry.Collection(property);
// get its associated CLR collection accessor
var accessor = dbItemsEntry.Metadata.GetCollectionAccessor();
// load the entry's items
await dbItemsEntry.LoadAsync();
// build a dictionary to track what needs to be added vs removed
var dbItemsMap = dbItemsEntry.CurrentValue.ToDictionary(e => e.Id);
// get the current items in the entity (not DB)
var items = (IEnumerable<Y>)accessor.GetOrCreate(entity, false);
// add them to the DB as needed
foreach (var item in items)
{
// if this already exists, no need to process it.
if (dbItemsMap.ContainsKey(item.Id))
dbItemsMap.Remove(item.Id);
else
{
// otherwise, add a tracked version of it.
context.Set<Y>().Attach(item);
accessor.Add(dbEntity, item, false);
}
}
// anything still left here has been deleted from the entity
foreach (var oldItem in dbItemsMap.Values)
accessor.Remove(dbEntity, oldItem);
// we have to clear the junction table from the incoming model's collection,
// otherwise EF will try to attach to it again, which will cause errors
// further down the line
var memberSelectorExpression = property.Body as MemberExpression;
if (memberSelectorExpression != null)
{
var propertyInfo = memberSelectorExpression.Member as PropertyInfo;
if (propertyInfo != null)
propertyInfo.SetValue(entity, null, null);
}
await context.SaveChangesAsync();
}
}
Using this is simple:
[HttpPut]
public async Task<IActionResult> UpdateFoo(EntityA model)
{
// update the junction table first
await context.UpdateJunctionTableAsync(model, x => x.Foo);
// then update whatever else you want
// e.g., if we were updating the whole row:
// context.EntityA.Attach(model).State = EntityState.Modified;
// save
await context.SaveChangesAsync();
return Ok();
}
I have asp.net core 2.2 project where I am creating the first migration for Entity framework core and I want to read the file image's title and create a list of objects to seed the database with said list of objects, I have a class
which inherits from interface IProductRepository said class contains a List of object Product I have been trying to find if with EF Core 2.2 I would be able to seed a List of products? without using any static method on the overload of OnModelCreating? or perhaps after creating the first migration?
public class ProductRepository : IProductRepository
public interface IProductRepository
{
Product AddProduct(Product p);
Product Delete(Guid Id);
Product UpdateProduct(Product p);
IEnumerable<Product> GetAllProduct();
Product GetProduct(Guid id);
IEnumerable<Product> GetProductBy(ProductType type);
}```
```public List<Product> productsList = new List<Product>();```
for anyone who has the same question I had found a solution a while back injecting the Interface and saving the migration programatically, to avoid conflicts remove any saved migration... and it would work. and dont do manual migrations
{
public static bool InitializeDB(this AppDbContext context, IProductRepository productRepositoryMock = null, IProductRepository mock= null)
{
var items = productRepositoryMock.GetAllProducts();
int count = 0;
foreach (var item in items)
{
var found = context.Products.Select(x => x.ProductName == item.ProductName).Any();
if (!found)
{
context.Products.Add(item);
count++;
}
}
context.SaveChanges();
context.initialized = 0x01;
return count > 0;
}
public static bool EnsureDatabaseIsSeeded(this IApplicationBuilder applicationBuilder, IProductRepositoryMock mock, IHostingEnvironment env, bool autoMigrateDatabase)
{
// seed the database using an extension method
using (var serviceScope = applicationBuilder.ApplicationServices
.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var ctx= serviceScope.ServiceProvider.GetService<AppDbContext>();
if (autoMigrateDatabase)
{
ctx.Database.Migrate();
}
var res = ctx.InitializeDB(mock);
serviceScope.ServiceProvider.GetService<AppDbContext>().Database.Migrate();
return res;
}
}
}
I am using the repository pattern to provide access to and saving of my aggregates.
The problem is the updating of aggregates which consist of a relationship of entities.
For example, take the Order and OrderItem relationship. The aggregate root is Order which manages its own OrderItem collection. An OrderRepository would thus be responsible for updating the whole aggregate (there would be no OrderItemRepository).
Data persistence is handled using Entity Framework 6.
Update repository method (DbContext.SaveChanges() occurs elsewhere):
public void Update(TDataEntity item)
{
var entry = context.Entry<TDataEntity>(item);
if (entry.State == EntityState.Detached)
{
var set = context.Set<TDataEntity>();
TDataEntity attachedEntity = set.Local.SingleOrDefault(e => e.Id.Equals(item.Id));
if (attachedEntity != null)
{
// If the identity is already attached, rather set the state values
var attachedEntry = context.Entry(attachedEntity);
attachedEntry.CurrentValues.SetValues(item);
}
else
{
entry.State = EntityState.Modified;
}
}
}
In my above example, only the Order entity will be updated, not its associated OrderItem collection.
Would I have to attach all the OrderItem entities? How could I do this generically?
Julie Lerman gives a nice way to deal with how to update an entire aggregate in her book Programming Entity Framework: DbContext.
As she writes:
When a disconnected entity graph arrives on the server side, the
server will not know the state of the entities. You need to provide a
way for the state to be discovered so that the context can be made
aware of each entity’s state.
This technique is called painting the state.
There are mainly two ways to do that:
Iterate through the graph using your knowledge of the model and set the state for each entity
Build a generic approach to track state
The second option is really nice and consists in creating an interface that every entity in your model will implement. Julie uses an IObjectWithState interface that tells the current state of the entity:
public interface IObjectWithState
{
State State { get; set; }
}
public enum State
{
Added,
Unchanged,
Modified,
Deleted
}
First thing you have to do is to automatically set the state to Unchanged for every entity retrieved from the DB, by adding a constructor in your Context class that hooks up an event:
public YourContext()
{
((IObjectContextAdapter)this).ObjectContext
.ObjectMaterialized += (sender, args) =>
{
var entity = args.Entity as IObjectWithState;
if (entity != null)
{
entity.State = State.Unchanged;
}
};
}
Then change your Order and OrderItem classes to implement the IObjectWithState interface and call this ApplyChanges method accepting the root entity as parameter:
private static void ApplyChanges<TEntity>(TEntity root)
where TEntity : class, IObjectWithState
{
using (var context = new YourContext())
{
context.Set<TEntity>().Add(root);
CheckForEntitiesWithoutStateInterface(context);
foreach (var entry in context.ChangeTracker
.Entries<IObjectWithState>())
{
IObjectWithState stateInfo = entry.Entity;
entry.State = ConvertState(stateInfo.State);
}
context.SaveChanges();
}
}
private static void CheckForEntitiesWithoutStateInterface(YourContext context)
{
var entitiesWithoutState =
from e in context.ChangeTracker.Entries()
where !(e.Entity is IObjectWithState)
select e;
if (entitiesWithoutState.Any())
{
throw new NotSupportedException("All entities must implement IObjectWithState");
}
}
Last but not least, do not forget to set the right state of your graph entities before calling ApplyChanges ;-) (You could even mix Modified and Deleted states within the same graph.)
Julie proposes to go even further in her book:
you may find yourself wanting to be more granular with the way
modified properties are tracked. Rather than marking the entire entity
as modified, you might want only the properties that have actually
changed to be marked as modified.
In addition to marking an entity as modified, the client is also
responsible for recording which properties have been modified. One way
to do this would be to add a list of modified property names to the
state tracking interface.
But as my answer is already too long, go read her book if you want to know more ;-)
My opinionated (DDD specific) answer would be:
Cut off the EF entities at the data layer.
Ensure your data layer only returns domain entities (not EF entities).
Forget about the lazy-loading and IQueryable() goodness (read: nightmare) of EF.
Consider using a document database.
Don't use generic repositories.
The only way I've found to do what you ask in EF is to first delete or deactivate all order items in the database that are a child of the order, then add or reactivate all order items in the database that are now part of your newly updated order.
So you have done well on update method for your aggregate root, look at this domain model:
public class ProductCategory : EntityBase<Guid>
{
public virtual string Name { get; set; }
}
public class Product : EntityBase<Guid>, IAggregateRoot
{
private readonly IList<ProductCategory> _productCategories = new List<ProductCategory>();
public void AddProductCategory(ProductCategory productCategory)
{
_productCategories.Add(productCategory);
}
}
it was just a product which has a product category, I've just created the ProductRepository as my aggregateroot is product(not product category) but I want to add the product category when I create or update the product in service layer:
public CreateProductResponse CreateProduct(CreateProductRequest request)
{
var response = new CreateProductResponse();
try
{
var productModel = request.ProductViewModel.ConvertToProductModel();
Product product=new Product();
product.AddProductCategory(productModel.ProductCategory);
_productRepository.Add(productModel);
_unitOfWork.Commit();
}
catch (Exception exception)
{
response.Success = false;
}
return response;
}
I just wanted to show you how to create domain methods for entities in domain and use it in service or application layer. as you can see the code below adds the ProductCategory category via productRepository in database:
product.AddProductCategory(productModel.ProductCategory);
now for updating the same entity you can ask for ProductRepository and fetch the entity and make changes on it.
note that for retrieving entity and value object of and aggregate separately you can write query service or readOnlyRepository:
public class BlogTagReadOnlyRepository : ReadOnlyRepository<BlogTag, string>, IBlogTagReadOnlyRepository
{
public IEnumerable<BlogTag> GetAllBlogTagsQuery(string tagName)
{
throw new NotImplementedException();
}
}
hope it helps
I have MVC web application project with Entity Framework code first. In this project I am going to use generic repository and unit of work patterns. Plus I want to use stored procedures for get list by and get-list methods.
How can I use stored procedures with generic repository and unit of work patterns?
To your generic repository add
public IEnumerable<T> ExecWithStoreProcedure(string query, params object[] parameters)
{
return _context.Database.SqlQuery<T>(query, parameters);
}
And then you can call it with any unitofwork/repository like
IEnumerable<Products> products =
_unitOfWork.ProductRepository.ExecWithStoreProcedure(
"spGetProducts #bigCategoryId",
new SqlParameter("bigCategoryId", SqlDbType.BigInt) { Value = categoryId }
);
You shouldn't be trying to use SPs with UoW/Repository pattern, because they are hard to control in code and often don't map back to the same entity type. UoW and Repository pattern are better suited to using ADO.NET directly and not Entity Framework, as EF is already a Repository pattern. I would suggest CQRS as a better pattern when using SPs. Elaborating on the answer by #sunil and my comment on it, I created a class specifically for handling stored procedures. It's easy to mock and test, too.
public class ProcedureManager : IProcedureManager
{
internal DbContext Context;
public ProcedureManager(DbContext context)
{
Context = context;
}
//When you expect a model back (async)
public async Task<IList<T>> ExecWithStoreProcedureAsync<T>(string query, params object[] parameters)
{
return await Context.Database.SqlQuery<T>(query, parameters).ToListAsync();
}
//When you expect a model back
public IEnumerable<T> ExecWithStoreProcedure<T>(string query)
{
return Context.Database.SqlQuery<T>(query);
}
// Fire and forget (async)
public async Task ExecuteWithStoreProcedureAsync(string query, params object[] parameters)
{
await Context.Database.ExecuteSqlCommandAsync(query, parameters);
}
// Fire and forget
public void ExecuteWithStoreProcedure(string query, params object[] parameters)
{
Context.Database.ExecuteSqlCommand(query, parameters);
}
}
For Generic Repository Add this :
public IEnumerable<TEntity> GetdataFromSqlcommand(string command, System.Data.SqlClient.SqlParameter[] parameter)
{
StringBuilder strBuilder = new StringBuilder();
strBuilder.Append($"EXECUTE {command}");
strBuilder.Append(string.Join(",", parameter.ToList().Select(s => $" #{s.ParameterName}")));
return Context.Set<TEntity>().FromSql(strBuilder.ToString(), parameter);
}
And you just need to send Stored Procedure name and the array of parameters :
public IEnumerable<MainData> GetMainData(Param query)
{
var param1 = new SqlParameter("param1", query.param1);
var param2 = new SqlParameter("param2", query.param2);
return GetdataFromSqlcommand("StoredProcedurename", parameter: new[] { param1, param2 }).ToList();
}
If you are using .net core 3.1, you have to make work around
You will create a class that will carry result of stored procedure
You will create another partial class from DBcontext and put inside it the previous class
You will create IStoredProcedure interface and implement it in stored procedure using generic
Inject your stored procedure class in startup class
Don't forget to make your result class fields, same as result form stored procedure
Execute the stored procedure
Implementation:
(1) first step
public class TaskPercents
{
public long Id { get; set; }
public long SchoolRepId { get; set; }
public string Name { get; set; }
}
(2) second step
public partial class SchoolsPartnershipDBContext : DbContext
{
public virtual DbSet<TaskPercents> TaskPercents { get; set; }
}
(3) third step
public interface IStoredProcedure<T>
{
public List<T> ExecuteStored(string query);
}
{
private SchoolsPartnershipDBContext _context;
public StoredProcedure(SchoolsPartnershipDBContext Context)
{
_context = Context;
}
public List<T> ExecuteStored(string query)
{
//Context = new SchoolsPartnershipDBContext();
var r = _context.Set<T>().FromSqlRaw(query);
return r.ToList();
// return null;
}
}
Last step
var result = _storedProcedure.ExecuteStored("TaskExecPercentForSchoolRep");
return result.ToList();
Hoping someone could clear things up. In the following ViewModel, does using Entity Framework as my model eliminate the need to use [Model] and [[ViewModelToModel(...)] attributes? The code runs the same with or without them, because the binding in the view ignores them and binds to the ObservableCollection.
Comments?
public class MainWindowViewModel : ViewModelBase
{
Models.OneHour_DataEntities ctx;
public MainWindowViewModel()
: base()
{
Save = new Command(OnSaveExecute, OnSaveCanExecute);
ctx = new Models.OneHour_DataEntities();
Customers = new ObservableCollection<Models.Customer>(ctx.Customers);
}
public ObservableCollection<Models.Customer> Customers
{
get { return GetValue<ObservableCollection<Models.Customer>>(CustomersProperty); }
set { SetValue(CustomersProperty, value); }
}
public static readonly PropertyData CustomersProperty = RegisterProperty("Customers", typeof(ObservableCollection<Models.Customer>), null);
public Command Save { get; private set; }
private bool OnSaveCanExecute()
{
return true;
}
private void OnSaveExecute()
{
ctx.SaveChanges();
}
}
Catel uses different interfaces to take advantage of the models. For example, it uses the following interfaces:
IEditableObject => undoing changes to model when user cancels
INotifyPropertyChanged => update view model when model updates
If your entity model implements these interfaces, you can define a property as a model.
In your example however, you use an ObservableCollection (thus a list of models) as a model. That is not supported (or, again, the collection must support IEditableObject and INotifyPropertyChanged).