How dependant is breezjs serverside contexprovider to entityframework? - breeze

I am building a WebApi for a CMS that has its own data provider. No DBContext or entity framework involved.
I have previously used breeze as it being such a breeze to map the server side model to the client:)
I have wondering if I can extend my code or breeze in a way such I get all the stuff from brezejs for free.
What I have to work with is the following Interfaces that I have made implementations for based on the data provider from the CMS.
public interface IC1Repository<T>
{
IQueryable<T> GetAll();
T Add(T item);
void Remove(T item);
bool Update(T item);
}
Its generic, so thats not going to work on the client.
I can generate a context class i guess that holds all the types exposed.
public class mycontext
{
public IC1Repository<Category> Categories { get; set; }
public IC1Repository<Customer> Customers { get; set; }
public IC1Repository<Employee> Employees { get; set; }
}
What would my next steps be to get this workign with breeze. Are there any interfaces i can implement such it mimics the DbContext. Can i maybe crate my custom DbSet that do not talk with a database, but just is a implementation of my IC1Repository above?
Any advices thanks :)

I think you want the ContextProvider which is the base class of the EFContextProvider.
That has the same semantics and same base behavior as the EFContextProvider but it doesn't use EF.
Check out the "No DB" sample which uses the ContextProvider to manage queries and saves to an in-memory "database".
Ignore the fact that this class sits in a DLL with references to EF. I realize that is annoying. But your project will compile and run just fine when there are no EF assemblies around. You can delete all the EF stuff if you used NuGet to get the Breeze.WebApi.dll.

Related

How Migration Works in Repository Pattern

Currently I am developing Large N-tire Application in Asp.Net MVC and
want to Separate Data,Entity,Service,Repository(Generic repository
with Unit Of works) I have reference Long Le article in Class
library project so I can reuse code in both controller and in Web API
Controller with code first entity framework and migration occurs if
model is changed.So,please suggest best approach for above
understanding?
As I have created separate project is there any effect in future while doing migration ?
You don't need repository pattern with Entity Framework Code First, because DbContext implements repository pattern and unit of work.
I usually define common database interface. Something like that:
public interface IDatabase
{
IDbSet<Plan> Plans { get; set; }
int SaveChanges();
}
Then I implement interface with my DbContext:
public class MyContext : DbContext, IDatabase
{
public IDbSet<Plan> Plans { get; set; }
// ...
}
You can create a context for testing purposes
public class MyMockContext : IDatabase
{
public IDbSet<Plan> Plans { get; set; }
// ...
}
But in your controller you always dependency-inject IDatabase. So that it's not dependent on any concrete implementation (and I use EFMock library in my tests).

Entity framework 6 providing repositories and UoW out of the box

But how do you use it?
I have a Code First project set up, and trying out some stuff with this new EF6. Reading all kinds of posts/blogs from at least 2 years old about EF4/5. But nothing whatsoever about EF6.
Let's say I have these entities:
public DbSet<Person> Persons { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<Invoice> Invoices { get; set; }
Do I still need to create repositories for each entity? Or would a class suffice with some methods to do some custom calculations aside from CRUD?
I know that this line:
kernel.Bind<MyDbContext>().ToSelf().InRequestScope();
Would suffice for DI, and that it will inject via constructor to upper layer classes where applicable.
The project has a class library and a web project asp.net-mvc. Where the class lib project contains my entities and has Migrations enabled.
Any light on this matter is really appreciated.
I've added a Repository layer on top of EF (which utilizes both Repository and UoW patterns inherently in its construction) in a couple of projects, and I've done that with one class that utilizes generics so that I only needed one file for all of my entities. You can decide if you want to do it or not, but I've found it useful in my projects.
My repositories have typically started out like what I've shown below, following up with more extension methods if/when I come across a need for them (obviously I'm not showing all of them, that's up for you to decide how to implement your repository).
public class Repository<T> : IRepository<T> where T : class
{
protected IDbContext Context;
protected DbSet<T> DbSet { get { return Context.Set<T>(); } }
public Repository(IDbContext context = null)
{
Context = context ?? new DbContext();
}
public void Add(T newRecord)
{
DbSet.Add(newRecord);
}
public void Update(T record)
{
var entry = Context.Entry(record);
DbSet.Attach(record);
entry.State = EntityState.Modified;
}
public void Remove(T record)
{
Context.Entry(record).State = EntityState.Deleted;
DbSet.Remove(record);
}
public IQueryable<T> Where(Expression<Func<T, bool>> predicate)
{
return DbSet.Where(predicate);
}
public bool Contains(Expression<Func<T, bool>> predicate)
{
return DbSet.Count(predicate) > 0;
}
public int Count(Expression<Func<T, bool>> predicate)
{
return DbSet.Count(predicate);
}
public int Save()
{
return Context.SaveChanges();
}
}
I've used repositories for 2 main reasons:
Unit testing. Doing this pattern allows me to fake the underlying data without having to have bad data in my database. All I need to do is simply create another implementation of IRepository that uses an in-memory list as its data source, and I'm all set for my pages to query that repository.
Extensibility. A fair number of times I've put in some methods into my repository because I found myself constantly doing the same logic with queries in my controllers. This has been extremely useful, especially since your client-side code doesn't need to know how it's doing it, just that it is doing it (which will make it easier if you need to change the logic of one file vs. multiple files).
This not all of it, obviously, but that should be enough for this answer. If you want to know more on this topic, I did write a blog post on it that you can find here.
Good luck on whatever you decide to do.
Entity Framework in itself can be considered a Repository. It facilitates work with data, in this case a database. This is all that a Repository does.
If you want to build another Repository on top of what EF provides, it is completely up to you - or to your business rules.
Many complex projects uses 2-3 layers of repositories with web services between. The performance is lower but you gain on other plans like security, resilience, separation of concerts, etc.
Your company might decide that it's in their best interest to never access data directly from front-end projects. They might force you to build a separate web-service project, which will be accessible only from localhost. So you will end up having EF as Repository in the webservice project. On the front-end side you will obviously need to build another Repository which will work with the web-service.
It also depends a lot of your project. If it's a small project it really it's overkill to build a second Repository on top of EF. But then again, read above. Nowadays security matters a lot more than performance.
To be politically correct I'm including the comment made by Wiktor Zychla:
"DbSet is a repository and DbContext is a Unit of Work. "Entity Framework is a Repository" could lead to unnecessary confusion."

What is the best way to use migrations with MVC5 and .Net Identity?

I'm just putting myself through the paces learning MVC5 with EF6 and Code First and have run into some confusion...
How are people managing their DbSets with the Identity changes, especially with Migrations?
Are you managing two sets of Migrations or putting your normal DbSets into the IdentityModel.cs file?
This is what I have currently:
public class ApplicationUser : IdentityUser
{
}
public class AoecContext : IdentityDbContext
{
public AoecContext()
: base("DefaultConnection")
{
}
public DbSet<Course> Courses { get; set; }
public DbSet<Faculty> People { get; set; }
public DbSet<SitePage> SitePages { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<SitePage>().HasOptional(p => p.CourseDetails);
}
}
Is that a good idea, or just plain bad?
Your concerns are a bit better separated if you keep your IdentityDbContext separate from your DomainDbContext, but then you would need to manage two sets of migrations (among other things). As you have it you'll only need one set of migrations. I wouldn't consider what you're doing "bad" necessarily- it really depends on the project.
If its any consolation, the project that we are currently working on uses only one DbContext that also inherits from IdentityDbContext as yours does. It does pull in some references to the Data Access project that I wish weren't there, but it does greatly simplify working with EF in terms of database generation, persistence, and migrations. Whether we'll outgrow it in the future or not is hard to say.

Accessing stored procedures on a code generated DbContext with Entity Framework 4.1 with DDD

I'm working on a large project using ASP.Net MVC 3, EF 4.1 and Ninject for Dependecy Injection. I've read through many of the existing questions here regarding DDD, EF and the Repository Pattern but I can't seem to find anyone incorporating stored procedures with these patterns.
I don't like the idea of implementing yet another repository pattern on top of what seems to already be a UnitOfWork/RepositoryPattern already defined with a DbContext. Also, I generally don't like the idea of creating Service and Repository classes for every type of entity in the system if possible.
The source of my problem stems from this common repository interface which everyone seems to use.
public interface IRepository<TEntity> where TEntity : class
{
TEntity Get(Expression<Func<TEntity, bool>> whereClause);
IEnumerable<TEntity> List();
IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> whereClause);
void Add(TEntity entity);
void Delete(TEntity entity);
// And so on...
}
That's great if all your queries can be in context of a single entity. Where this breaks for me is when I want to access a stored procedure. With EF 4.1 & Code Generatrion you can add stored procedures (e.g. SelectUser) and it will generate a context which looks something like this.
namespace MyCompany.Data.Database
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Objects;
using MyCompany.Domain.Entities;
using MyCompany.Domain.Contracts;
public partial class MyCompanyEntities : DbContext
{
public MyCompanyEntities()
: base("name=MyCompanyEntities")
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<Order> Orders { get; set; }
public DbSet<User> Users { get; set; }
public virtual ObjectResult<User> SelectUser(Nullable<int> userId)
{
((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace.LoadFromAssembly(typeof(User).Assembly);
var userIdParameter = userId.HasValue ?
new ObjectParameter("UserId", userId) :
new ObjectParameter("UserId", typeof(int)); MyCompanyEntities x; x.
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<User>("SelectUser", userIdParameter);
}
public virtual ObjectResult<User> SelectUser(Nullable<int> userId, MergeOption mergeOption)
{
((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace.LoadFromAssembly(typeof(User).Assembly);
var userIdParameter = userId.HasValue ?
new ObjectParameter("UserId", userId) :
new ObjectParameter("UserId", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<User>("SelectUser", mergeOption, userIdParameter);
}
}
}
As part of my DDD setup I have a UserService class and I would like to 'inject' a repository to its constructor. Many examples suggest that the constructor should accept an (IRepository<User> userRepository). This doesn't work for me. Stored procedures are generated on the DbContext class as a method and I am unable to see it.
The only thing I can think of is to either create another interface with the stored procedure methods on it. I don't really want to add it to the generic IRepository because then when you have an instance of IRepository<Order> you'll still see SelectUser which seems a bit odd. Maybe it's not a big deal?
Perhaps I'm going about this the wrong way. Should I not be bothering with creating an interface on top of my DbContext if I'm not trying to create a whole new repository pattern? I was really creating it for the dependency injection. Would it be wrong if the UserService constructor took a MyCompanyEntities instance instead of an interface?
What you found is natural. The problem is that generic repository is insufficient for real scenarios. It is only good for "base" implementation. You need specific repository for User entity which will expose method wrapping call to context exposed stored procedure.

ASP.NET MVC: BLL and DAL to Repository design

We are moving from ASP.NET Web Forms to MVC 2.0. In most of our projects we have a typical setup to communicate with a database.
Common (objects/entities like 'SiteMenu' and 'Users')
Business Logic Layer (with calls to de Data Access Layer)
Data Access Layer
The DAL has a DatabaseHelper with common database operation, an OdbcHelper with database specific operations (eg MySQL) and a StoredProcedure class with all the stored procedures.
How is this design translated into a repository design? We want to use our own database helpers instead of NHibernate etc.
What would you suggest?
You could leverage repositories using every data access technology.
An repository is abstraction over existing data access helpers / services, allowing decoupling of the business logic from the data access layer. Repositories used together with Query to enable filtering. It is often used together with unit of work to store the changes back into database.
A repository has at least:
Get-object-by-key operation(s)
Get-all-objects operation
Get-first-object-by-query operation(s)
Get-objects-by-query operation(s)
A very simple example :):
A. Product class , defined in Common:
public class Product
{
public int Id { get; private set; }
public string Code { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
B. Classes for Query, IRepository and IUnitOfWork are defined in DAL.interfaces.dll or Common.dll (but NOT in DAL!).
public class Query
{
public string Text { get; set; }
}
public interface IRepository<TEntity>
where TEntity : class
{
bool TryGet(int key, out TEntity value);
TEntity this[int key] { get; }
IEnumerable<TEntity> GetAll();
bool TryGetFirst(Query condition, out TEntity value);
TEntity GetFirst(Query condition);
IEnumerable<TEntity> GetAll(Query condition);
int Count { get; }
}
public interface IUnitOfWork
{
void SetAdded(TEntity value); // Marks entity as added for further INSERT
void SetRemoved(TEntity value); // Marks entity as removed for further DELETE
void SetChanged(TEntity value); // Marks entity as modified for further UPDATE
void Save(); // Save all the changes
}
IUnitOfWork is aware of the changed entities. Save() calls an appropriate DatabaseHelper / OdbcHelper CRUD method for every changed entity in order to persist the changes in the database.
The implementation of IRepository<Product>, ... IRepository<EntityXY> and IUnitOFWork should be placed in DAL. The BLL then uses IRepository and IUnitOFWork in order to implement business (domain) logic. The BLL itself could be organized as service layer on the top of domain model, but it is out of the scope of the discussion :).
I hope my answer helps.
Please feel free to ask me a question ...
Links:
Patterns of enterpise application architecture by Martin Fowler
You can maintain the same layered approach when moving to MVC. Your BLL that returns entities/objects can be your M in MVC. Often you'll see in samples where people create an instance of the repository directly in their Controller, in your case you'll be creating an instance of your BLL class.

Resources