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).
Related
We have an application that uses multiple databases for different users. We are using a generic repository and unit-of-work pattern and dependency injection. We have a DbContext which is a parameterized one. What we want is when users comes to our website, we want the DbContext point to their website for that particular transaction.
We tried registering the DbContext on the unity configuration and override it in the controller level. But that failed. Can anyone let us know how to get it done?
DBContext
public class TimperContext: IdentityDbContext<MyUser>
{
public TimperContext(string connectionString) : base(connectionString) { }
public DbSet<UserAddress> UserAddresses { get; set; }
}
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.
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.
i have a problem with my mvc3 application, i need to create some Validation stuff. but i dont have a normal model class because i have used EF with the database first approach.
i can not just open the class and write something like:
[Required]
[StringLength(10)]
how to solve this problem?
You could use the MetadataType attribute. So let's suppose that EF spit at your face the following class which you cannot modify:
public partial class Foo
{
public string Bar { get; set; }
}
Now you could extend it since it is a partial class:
[MetadataType(typeof(FooMetadata))]
public partial class Foo
{
}
and then define the metadata:
public class FooMetadata
{
[Required]
[StringLength(10)]
public string Foo { get; set; }
}
Or, simply throw data annotations away and use a real validation framework such as FluentValidation.NET (which I use and strongly recommend) allowing you to express complex validation rules on your models in a fluent manner, has an excellent integration with ASP.NET MVC and also allows you to elegantly unit test your vaildation logic in isolation.
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.