entity framework unit of work in winforms - entity-framework

I found this sample but its for web. Can any one check this proj. and add a simple sample using winforms(no wpf).
Source Code
Thx

What kind of problem were you facing? Anyways I have made sample (yet basic) structure of how you can achieve this in WinForm. I have done using sort of Model View Presenter pattern.
First of all we have a presenter, which would deal with unit of work almost similarly the way controller does
internal class EmployeePresenter
{
private readonly IEmployeeFormView _employeeFormView;
private readonly IUnitOfWork _unitOfWork;
public EmployeePresenter(IEmployeeFormView view)
{
_employeeFormView = view;
_unitOfWork = new SqlUnitOfWork();
}
internal void GetData()
{
var id = 1; //parameter
var employee = _unitOfWork.Employees.Single(e => e.Id == id);
_employeeFormView.PopulateData(employee.Name);
}
}
Then we have an interface and a form implementing that interface
public interface IEmployeeFormView
{
void PopulateData(string data);
}
public partial class EmployeeForm : Form, IEmployeeFormView
{
private readonly EmployeePresenter _presenter;
public EmployeeForm()
{
InitializeComponent();
_presenter = new EmployeePresenter(this);
}
#region IEmployeeFormView Members
public void PopulateData(string data)
{
txtName.Text = data; //txtName is a textbox on form
}
#endregion
private void btnGet_Click(object sender, EventArgs e)
{
_presenter.GetData();
}
}
Add the required reference and you are done. This might not be the best way but it's certainly a way to achieve this.
Solution is upload here.
Hope this helps. Please feel free to discuss, if required.

Related

Using Microsoft.AspNetCore.Identity.MongoDB for Multi Tenancy. How do we inject dynamic Tenant into MongoDbContext

Does anyone know how we can inject context into User Manager > MongoDB serStore at runtime in .net core 2.0.
We cannot do this at startup due to the context being dynamic but the UserStore is not accessible and UserManager has too many variables to new up, and it is wrong. Are there any solutions?
public class UserStore<TUser> :
IUserPasswordStore<TUser>,
IUserRoleStore<TUser>,
IUserLoginStore<TUser>,
IUserSecurityStampStore<TUser>,
IUserEmailStore<TUser>,
IUserClaimStore<TUser>,
IUserPhoneNumberStore<TUser>,
IUserTwoFactorStore<TUser>,
IUserLockoutStore<TUser>,
IQueryableUserStore<TUser>,
IUserAuthenticationTokenStore<TUser>
where TUser : IdentityUser
{
private readonly IMongoCollection<TUser> _Users;
//THIS IS WHERE WE WANT TO INJECT THE users AT RUNTIME
public UserStore(IMongoCollection<TUser> users)
{
_Users = users;
}
public virtual void Dispose()
{
// no need to dispose of anything, mongodb handles connection pooling automatically
}
public virtual async Task<IdentityResult> CreateAsync(TUser user, CancellationToken token)
{
await _Users.InsertOneAsync(user, cancellationToken: token);
return IdentityResult.Success;
}
unfortunately users is null at startup, and should be as the tenant has not been created at that point.
We have also been using the saaskit.Multitenancy and just can't find a solution.
Any help would be much appreciated.
Thanks
i think u need a generic repository to act as a wrapper for IMongoCollection then inject the repository inside controllers
public class Repository<T>
{
public IMongoCollection<T> Collection { get; private set; }
public Repository(IDbFactory dbFactory)
{
MongoClient client = new MongoClient("ur connection string");
this.Collection = client.GetDatabase("db").GetCollection<T>(typeof(T).Name);
}
public T Find(Expression<Func<T, bool>> filter)
{
return this.Collection.AsQueryable<T>().FirstOrDefault<T>(filter);
}
public async Task<T> FindAsync(Expression<Func<T, bool>> filter)
{
return await this.Collection.AsQueryable<T>().FirstOrDefaultAsync<T>(filter);
}
// here add more methods
}
then register the dependency as below inside Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient(typeof(IRepository<>), typeof(Repository<>));
services.AddMvc();
}
finally inside controllers u inject the generic repository, also dont forget to Implement the IDisopsible in genereic repository
public class ProductController : Controller
{
private readonly IRepository<Product> _productRepository = null;
public ProductController(IRepository<Product> productRepository)
{
this._productRepository = productRepository;
}
}

System.Reactive: Implement an IObservable<T>

I need to create a custom IObservable. I've read a bit over there, I've ended up I shouldn't implement IObservable<T> directly.
I've noticed that there is an ObservableBase<T>. This is an abstract class, so I need to implement the abstract method:
public class Store<TState> : ObservableBase<TState>, IObserver<IAction>
{
public void OnCompleted()
{
throw new NotImplementedException();
}
public void OnError(Exception error)
{
throw new NotImplementedException();
}
public void OnNext(IAction value)
{
throw new NotImplementedException();
}
protected override IDisposable SubscribeCore(IObserver<TState> observer)
{
>>>>>>>>>>>>>>>>>******<<<<<<<<<<<<<<<<<<<<<<<
throw new NotImplementedException();
}
}
How should I implement this method?
I don't know your problem, but if you can replace implementing IObservable for exposing a property/method that returns IObservable you'll be a lot better off. If you can do that, you can easily return an Rx-based Observable from some of Rx's create methods.
If you can't do that, I would recommend wrapping a Subject<T>:
public class MyIntObservable : IObservable<int>
{
private readonly Subject<int> _mySubject = new Subject<int>();
public IDisposable Subscribe(IObserver<int> observer)
{
return _mySubject.Subscribe(observer);
}
}
I'm guessing you don't want to be doing what you are doing.
From a brief look at the "Store" class that you want to mimic, it appears to be some sort of Subject. A Subject is both a IObserver and an IObservable and there are many implementations that are provided out of the box. Here is the interface:
public interface ISubject<in TSource, out TResult> : IObserver<TSource>, IObservable<TResult>
{
}
This is a very good article about Subjects and when to use them here:
http://davesexton.com/blog/post/To-Use-Subject-Or-Not-To-Use-Subject.aspx

What's DataService Best practice using Entity Framework and Repository and UnitOfWork Patterns

I'm using EF and MVVM pattern. My question is about the Data Access Layer. in DAL I have the following classes:
MyObjectContext which is technically the standard ObjectContext now, but some Unit-of-work methods will be added to it later.
Repository<TModel> which handles the most needed queries (such as Add, GetAll, ...) on different ObjectSets.
A bunch of DataServices which make use of repositories to provide a higher level of data access for Core.
The project I'm working on is a business application with about 100 EntitySets so far, and there are times when a single interaction of a user can involve up to 20 different EntitySets (updating most of them). I currently add .Include(params string[]) to my queries to prevent ObjectContextDisposedException but it doesn't seem to be a reliable solution.
The question is should I create an instance of MyObjectContext (and therefore Repository) in each of DataService methods (like the following codes, it seems to me that the ability of Unit of work would be useless in this case) or should I create it outside of DataService and pass it to the DataServices through their constructors (or directly to each of the DataService methods) to handle a bunch of database actions (different tables and queries) together. And how?
Here's what MyObjectContext looks like:
public class MyObjectContext : ObjectContext, IUnitOfWork
{
public MyObjectContext()
: base("name=EdmContainer", "EdmContainer")
{
ContextOptions.LazyLoadingEnabled = true;
}
#region IUnitOfWork Members
public void Commit()
{
SaveChanges();
}
#endregion
}
This is how Repository looks like:
public class Repository<TModel>
{
private readonly SoheilEdmContext _context;
public Repository(IUnitOfWork unitOfWork)
{
if (unitOfWork == null)
throw new ArgumentNullException("unitOfWork");
_context = unitOfWork as SoheilEdmContext;
}
public TModel FirstOrDefault(Expression<Func<TModel, bool>> where)
{
return _context.CreateObjectSet<TModel>().FirstOrDefault(where);
}
public void Add(TModel entity)
{
_context.CreateObjectSet<TModel>().AddObject(entity);
}
...
}
And this is how a common DataService looks like:
public class JobDataService : IDataService<Job>
{
#region IDataService<Job> Members
public Job GetSingle(int id)
{
Job model = null;
using (var context = new MyObjectContext())
{
var repos = new Repository<Job>(context);
model = repos.FirstOrDefault(x => x.Id == id);
}
return model;
}
public IEnumerable<Job> GetAll()
{
using (var context = new MyObjectContext())
{
var repos = new Repository<Job>(context);
var models = repos.GetAll();
return models;
}
}
public IEnumerable<Job> GetActives()
{
throw new NotImplementedException();
}
public int AddModel(Job model)
{
using (var context = new MyObjectContext())
{
var repos = new Repository<Job>(context);
repos.Add(model);
context.SaveChanges();
}
}
public void UpdateModel(Job model)
{
throw new NotImplementedException();
}
public void DeleteModel(Job model)
{
using (var context = new MyObjectContext())
{
var repos = new Repository<Job>(context);
var model = repos.FirstOrDefault(x => x.Id == model.Id);
if (model == null) return;
repos.Delete(model);
context.SaveChanges();
}
}
#endregion
}
Any kind of idea or insight would be appreciated.
You can create an instance of MyObjectContext in each service, like JobDataService, however, it makes your code messy and it is hard to maintain. Create instance of MyObjectContext outside of DataService is better. What you have now, if you have 100 EntitySets, you have to create 100 DataServices. That is because the use of "Repository Pattern" and "UnitOfWork" here is not efficient. I would suggest doing the following:
ObjectContext
public class MyObjectContext : ObjectContext
{
public MyObjectContext() : base("name=EdmContainer", "EdmContainer")
{
ContextOptions.LazyLoadingEnabled = true;
}
#region IUnitOfWork Members
public void Commit()
{
SaveChanges();
}
#endregion
}
Generic Repository
public interface IRepository<TModel> where TModel : class
{
void Add(TModel entity);
IEnumerable<TModel> GetAll();
// Do some more implement
}
public class Repository<TModel> : IRepository<TModel> where TModel : class
{
private readonly ObjectContext _context;
public Repository(ObjectContext context)
{
_context = context;
}
public virtual void Add(TModel entity)
{
_context.CreateObjectSet<TModel>().AddObject(entity);
}
public virtual IEnumerable<TModel> GetAll()
{
return _context.CreateObjectSet<TModel>();
}
}
UnitOfWork
public interface IUnitOfWork : IDisposable
{
IRepository<Job> Jobs { get; }
IRepository<User> Users { get;}
void Commit();
}
public class UnitOfWork : IUnitOfWork
{
private readonly SoheilEdmContext _context;
private readonly IRepository<Job> _jobRepository;
private readonly IRepository<User> _userRepository;
public UnitOfWork(SoheilEdmContext context)
{
_context = context;
_jobRepository = new Repository<Job>(_context);
_userRepository = new Repository<User>(_context);
}
public IRepository<Job> Jobs{get { return _jobRepository; }}
public IRepository<User> Users{get { return _userRepository; }}
public void Commit(){_context.Commit();}
public void Dispose()
{
if (_context != null)
{
_context.Dispose();
}
GC.SuppressFinalize(this);
}
JodDataSerivce
public interface IDataService
{
IEnumerable<Job> GetAll();
}
public class DataService : IDataService
{
private readonly IUnitOfWork _unitOfWork;
public DataService(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public IEnumerable<Job> GetAll()
{
return _unitOfWork.Jobs.GetAll();
}
}
Here I used interface for implementing everything, if you want to do the same, you need to use IoC Container. I used the "Simple Injector", you can find it here:
Simple Injector
One more suggestion, if you feel like you have too many I/O operations to implement, like database access, querying data, etc., you should consider using Asynchronous. Below is a good video on Asynchronous.
How to Build ASP.NET Web Applications Using Async

Entity Framework Unity of Work and Repository pattern

I'm trying to implement UoW and Repository pattern, but I get error
An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
I know that I get that error because I have two repositories which create two different DBContext, but I don't know why that happens.
Here is my code for UoW
public class UnitOfWorkRepositoryRepository : IUnitOfWorkRepository
{
private readonly IDatabaseFactory _databaseFactory;
private DatabaseContext _databaseContext;
public UnitOfWorkRepositoryRepository(IDatabaseFactory databaseFactory)
{
_databaseFactory = databaseFactory;
}
public DatabaseContext Database
{
get { return _databaseContext ?? (_databaseContext = _databaseFactory.GetDatabaseContext()); }
}
public void Save()
{
_databaseContext.Save();
}
}
And here sample Repository:
private static readonly DatabaseFactory DatabaseFactory = new DatabaseFactory();
private static readonly UnitOfWorkRepositoryRepository UnitOfWorkRepositoryRepository = new UnitOfWorkRepositoryRepository(DatabaseFactory);
public User GetUserById(int id)
{
return UnitOfWorkRepositoryRepository.Database.Users.SingleOrDefault(u => u.UserId.Equals(id));
}
What's wrong ? how should I implement UoW
P.S.
I'm not getting any errors in this repository, but other one was too long, this one serves just as sample.
Did you try this
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
I think it is more descriptive, I have ever seen.
Have a look at this SO answer where I describe a way to decoulple Uow from Repository.

My MVC Custom ControllerFactory works but could it be better?

I've looked at Ninject, StructureMap and Other Dependency Injection and Service Locator frameworks, but this question is more about learning how it works and what can be better. More to the point, I’m not interesting in looking at a Framework’s source code for Dependency Injection, but understanding how it’s achieved from beginning to end in practice/code.
The code below is for a small internal project, so with that in mind let me begin.
Here is my interface for returning Domain Models to my controllers. I've decided that due to the size of the project (small), a single interface for Controllers was acceptable.
interface IModelFactory
{
IEnumerable<User> GetUsers();
User GetUser(Guid UserID);
bool Add(User User);
bool Delete(User User);
bool Update(User User);
IEnumerable<Car> GetCars();
Car GetCar(Guid CarID);
bool Add(Car Car);
bool Delete(Car Car);
bool Update(Car Car);
}
Each controller has inherits from DIBaseController so I didn't have to create private members for every controller.
public abstract class DIBaseController : Controller
{
protected IModelFactory ModelFactory { get; set; }
public DIBaseController(IModelFactory ModelFactory)
{
this.ModelFactory = ModelFactory;
}
}
public class HomeController : DIBaseController
{
public HomeController (IModelFactory ModelFactory)
: base(ModelFactory)
{
}
}
Created my own Controller Factory that allows me to inject my ModelFactory into Controllers.
internal class DIControllerFactory : DefaultControllerFactory
{
private IModelFactory _ModelFactory;
internal DIControllerFactory(IModelFactory ModelFactory)
{
this._ModelFactory = ModelFactory;
}
public override IController CreateController(RequestContext requestContext, string controllerName)
{
IController result = null;
string thisnamespace = this.GetType().Namespace;
//This could be improved I bet.
Type controller = Type.GetType(thisnamespace.Substring(0, thisnamespace.IndexOf('.')) + ".Controllers." + controllerName + "Controller");
if (controller != null
&& controller.IsSubclassOf(typeof(DIBaseController)))
{
result = (IController)Activator.CreateInstance(controller, new object[] { this._ModelFactory });
}
else
{
result = base.CreateController(requestContext, controllerName);
}
return result;
}
}
And finally added the code to Inject the Concreate class into the Factory to inject into created Controllers.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
ControllerBuilder.Current.SetControllerFactory(new DIControllerFactory(new LinqSqlModelFactory()));
}
The only area I haven't explored (and I don't think I'm interested in at the moment) is to create a web.config section to dynamically create the ModelFactory. This works, but I'm interested if I've completely missed the boat, come close, or if I'm spot on?
Instead of overriding CreateController use
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
It gives you the controller type and the first part of your implementation is obsolete.
The next point you have to improve is that you analyze the parameters of the constructor and pass an instance of those parameters which are created using some configuration instead of guessing that there is exactly one parameter IModelFactory.