Search Results

Search found 122 results on 5 pages for 'irepository'.

Page 2/5 | < Previous Page | 1 2 3 4 5  | Next Page >

  • DCI: How to implement Context with Dependency Injection?

    - by ciscoheat
    Most examples of a DCI Context are implemented as a Command pattern. When using Dependency Injection though, it's useful to have the dependencies injected in the constructor and send the parameters into the executing method. Compare the Command pattern class: public class SomeContext { private readonly SomeRole _someRole; private readonly IRepository<User> _userRepository; // Everything goes into the constructor for a true encapsuled command. public SomeContext(SomeRole someRole, IRepository<User> userRepository) { _someRole = someRole; _userRepository = userRepository; } public void Execute() { _someRole.DoStuff(_userRepository); } } With the Dependency injected class: public class SomeContext { private readonly IRepository<User> _userRepository; // Only what can be injected using the DI provider. public SomeContext(IRepository<User> userRepository) { _userRepository = userRepository; } // Parameters from the executing method public void Execute(SomeRole someRole) { someRole.DoStuff(_userRepository); } } The last one seems a bit nicer, but I've never seen it implemented like this so I'm curious if there are any things to consider.

    Read the article

  • Dynamic casting using a generic interface

    - by Phil Whittaker
    Hi Is there any way to cast to a dynamic generic interface.. Site s = new Site(); IRepository<Site> obj = (IRepository<s.GetType()>)ServiceLocator.Current.GetInstance(t) obviously the above won't compile with this cast. Is there anyway to do a dynamic cast of a generic interface. I have tried adding a non generic interface but the system is looses objects in the Loc container. Thanks Phil

    Read the article

  • Trouble with abstract generic methods

    - by DanM
    Let's say I have a class library that defines a couple entity interfaces: public interface ISomeEntity { /* ... */ } public interface ISomeOtherEntity { /* ... */ } This library also defines an IRepository interface: public interface IRepository<TEntity> { /* ... */ } And finally, the library has an abstract class called RepositorySourceBase (see below), which the main project needs to implement. The goal of this class is to allow the base class to grab new Repository objects at runtime. Because certain repositories are needed (in this example a repository for ISomeEntity and ISomeOtherEntity), I'm trying to write generic overloads of the GetNew<TEntity>() method. The following implementation doesn't compile (the second GetNew() method gets flagged as "already defined" even though the where clause is different), but it gets at what I'm trying to accomplish: public abstract class RepositorySourceBase // This doesn't work! { public abstract Repository<TEntity> GetNew<TEntity>() where TEntity : SomeEntity; public abstract Repository<TEntity> GetNew<TEntity>() where TEntity : SomeOtherEntity; } The intended usage of this class would be something like this: public class RepositorySourceTester { public RepositorySourceTester(RepositorySourceBase repositorySource) { var someRepository = repositorySource.GetNew<ISomeEntity>(); var someOtherRepository = repositorySource.GetNew<ISomeOtherEntity>(); } } Meanwhile, over in my main project (which references the library project), I have implementations of ISomeEntity and ISomeOtherEntity: public class SomeEntity : ISomeEntity { /* ... */ } public class SomeOtherEntity : ISomeOtherEntity { /* ... */ } The main project also has an implementation for IRepository<TEntity>: public class Repository<TEntity> : IRepository<TEntity> { public Repository(string message) { } } And most importantly, it has an implementation of the abstract RepositorySourceBase: public class RepositorySource : RepositorySourceBase { public override Repository<SomeEntity> GetNew() { return new Repository<SomeEntity>("stuff only I know"); } public override Repository<SomeOtherEntity> GetNew() { return new Repository<SomeOtherEntity>("other stuff only I know"); } } Just as with RepositorySourceBase, the second GetNew() method gets flagged as "already defined". So, C# basically think I'm repeating the same method because there's no way to distinguish the methods from parameters, but if you look at my usage example, it seems like I should be able to distinguish which GetNew() I want from the generic type parameter, e.g, <ISomeEntity> or <ISomeOtherEntity>. What do I need to do to get this to work?

    Read the article

  • Creating a dynamic proxy generator with c# – Part 2 – Interceptor Design

    - by SeanMcAlinden
    Creating a dynamic proxy generator – Part 1 – Creating the Assembly builder, Module builder and caching mechanism For the latest code go to http://rapidioc.codeplex.com/ Before getting too involved in generating the proxy, I thought it would be worth while going through the intended design, this is important as the next step is to start creating the constructors for the proxy. Each proxy derives from a specified type The proxy has a corresponding constructor for each of the base type constructors The proxy has overrides for all methods and properties marked as Virtual on the base type For each overridden method, there is also a private method whose sole job is to call the base method. For each overridden method, a delegate is created whose sole job is to call the private method that calls the base method. The following class diagram shows the main classes and interfaces involved in the interception process. I’ll go through each of them to explain their place in the overall proxy.   IProxy Interface The proxy implements the IProxy interface for the sole purpose of adding custom interceptors. This allows the created proxy interface to be cast as an IProxy and then simply add Interceptors by calling it’s AddInterceptor method. This is done internally within the proxy building process so the consumer of the API doesn’t need knowledge of this. IInterceptor Interface The IInterceptor interface has one method: Handle. The handle method accepts a IMethodInvocation parameter which contains methods and data for handling method interception. Multiple classes that implement this interface can be added to the proxy. Each method override in the proxy calls the handle method rather than simply calling the base method. How the proxy fully works will be explained in the next section MethodInvocation. IMethodInvocation Interface & MethodInvocation class The MethodInvocation will contain one main method and multiple helper properties. Continue Method The method Continue() has two functions hidden away from the consumer. When Continue is called, if there are multiple Interceptors, the next Interceptors Handle method is called. If all Interceptors Handle methods have been called, the Continue method then calls the base class method. Properties The MethodInvocation will contain multiple helper properties including at least the following: Method Name (Read Only) Method Arguments (Read and Write) Method Argument Types (Read Only) Method Result (Read and Write) – this property remains null if the method return type is void Target Object (Read Only) Return Type (Read Only) DefaultInterceptor class The DefaultInterceptor class is a simple class that implements the IInterceptor interface. Here is the code: DefaultInterceptor namespace Rapid.DynamicProxy.Interception {     /// <summary>     /// Default interceptor for the proxy.     /// </summary>     /// <typeparam name="TBase">The base type.</typeparam>     public class DefaultInterceptor<TBase> : IInterceptor<TBase> where TBase : class     {         /// <summary>         /// Handles the specified method invocation.         /// </summary>         /// <param name="methodInvocation">The method invocation.</param>         public void Handle(IMethodInvocation<TBase> methodInvocation)         {             methodInvocation.Continue();         }     } } This is automatically created in the proxy and is the first interceptor that each method override calls. It’s sole function is to ensure that if no interceptors have been added, the base method is still called. Custom Interceptor Example A consumer of the Rapid.DynamicProxy API could create an interceptor for logging when the FirstName property of the User class is set. Just for illustration, I have also wrapped a transaction around the methodInvocation.Coninue() method. This means that any overriden methods within the user class will run within a transaction scope. MyInterceptor public class MyInterceptor : IInterceptor<User<int, IRepository>> {     public void Handle(IMethodInvocation<User<int, IRepository>> methodInvocation)     {         if (methodInvocation.Name == "set_FirstName")         {             Logger.Log("First name seting to: " + methodInvocation.Arguments[0]);         }         using (TransactionScope scope = new TransactionScope())         {             methodInvocation.Continue();         }         if (methodInvocation.Name == "set_FirstName")         {             Logger.Log("First name has been set to: " + methodInvocation.Arguments[0]);         }     } } Overridden Method Example To show a taster of what the overridden methods on the proxy would look like, the setter method for the property FirstName used in the above example would look something similar to the following (this is not real code but will look similar): set_FirstName public override void set_FirstName(string value) {     set_FirstNameBaseMethodDelegate callBase =         new set_FirstNameBaseMethodDelegate(this.set_FirstNameProxyGetBaseMethod);     object[] arguments = new object[] { value };     IMethodInvocation<User<IRepository>> methodInvocation =         new MethodInvocation<User<IRepository>>(this, callBase, "set_FirstName", arguments, interceptors);          this.Interceptors[0].Handle(methodInvocation); } As you can see, a delegate instance is created which calls to a private method on the class, the private method calls the base method and would look like the following: calls base setter private void set_FirstNameProxyGetBaseMethod(string value) {     base.set_FirstName(value); } The delegate is invoked when methodInvocation.Continue() is called within an interceptor. The set_FirstName parameters are loaded into an object array. The current instance, delegate, method name and method arguments are passed into the methodInvocation constructor (there will be more data not illustrated here passed in when created including method info, return types, argument types etc.) The DefaultInterceptor’s Handle method is called with the methodInvocation instance as it’s parameter. Obviously methods can have return values, ref and out parameters etc. in these cases the generated method override body will be slightly different from above. I’ll go into more detail on these aspects as we build them. Conclusion I hope this has been useful, I can’t guarantee that the proxy will look exactly like the above, but at the moment, this is pretty much what I intend to do. Always worth downloading the code at http://rapidioc.codeplex.com/ to see the latest. There will also be some tests that you can debug through to help see what’s going on. Cheers, Sean.

    Read the article

  • Fake It Easy On Yourself

    - by Lee Brandt
    I have been using Rhino.Mocks pretty much since I started being a mockist-type tester. I have been very happy with it for the most part, but a year or so ago, I got a glimpse of some tests using Moq. I thought the little bit I saw was very compelling. For a long time, I had been using: 1: var _repository = MockRepository.GenerateMock<IRepository>(); 2: _repository.Expect(repo=>repo.SomeCall()).Return(SomeValue); 3: var _controller = new SomeKindaController(_repository); 4:  5: ... some exercising code 6: _repository.AssertWasCalled(repo => repo.SomeCall()); I was happy with that syntax. I didn’t go looking for something else, but what I saw was: 1: var _repository = new Mock(); And I thought, “That looks really nice!” The code was very expressive and easier to read that the Rhino.Mocks syntax. I have gotten so used to the Rhino.Mocks syntax that it made complete sense to me, but to developers I was mentoring in mocking, it was sometimes to obtuse. SO I thought I would write some tests using Moq as my mocking tool. But I discovered something ugly once I got into it. The way Mocks are created makes Moq very easy to read, but that only gives you a Mock not the object itself, which is what you’ll need to pass to the exercising code. So this is what it ends up looking like: 1: var _repository = new Mock<IRepository>(); 2: _repository.SetUp(repo=>repo.SomeCall).Returns(SomeValue); 3: var _controller = new SomeKindaController(_repository.Object); 4: .. some exercizing code 5: _repository.Verify(repo => repo.SomeCall()); Two things jump out at me: 1) when I set up my mocked calls, do I set it on the Mock or the Mock’s “object”? and 2) What am I verifying on SomeCall? Just that it was called? that it is available to call? Dealing with 2 objects, a “Mock” and an “Object” made me have to consider naming conventions. Should I always call the mock _repositoryMock and the object _repository? So I went back to Rhino.Mocks. It is the most widely used framework, and show other how to use it is easier because there is one natural object to use, the _repository. Then I came across a blog post from Patrik Hägne, and that led me to a post about FakeItEasy. I went to the Google Code site and when I saw the syntax, I got very excited. Then I read the wiki page where Patrik stated why he wrote FakeItEasy, and it mirrored my own experience. So I began to play with it a bit. So far, I am sold. the syntax is VERY easy to read and the fluent interface is super discoverable. It basically looks like this: 1: var _repository = A.Fake<IRepository>(); 2: a.CallTo(repo=>repo.SomeMethod()).Returns(SomeValue); 3: var _controller = new SomeKindaController(_repository); 4: ... some exercising code 5: A.CallTo(() => _repository.SOmeMethod()).MustHaveHappened(); Very nice. But is it mature? It’s only been around a couple of years, so will I be giving up some thing that I use a lot because it hasn’t been implemented yet? I doesn’t seem so. As I read more examples and posts from Patrik, he has some pretty complex scenarios. He even has support for VB.NET! So if you are looking for a mocking framework that looks and feels very natural, try out FakeItEasy!

    Read the article

  • Using IOC in a remoting scenario

    - by Christoph
    I'm struggling with getting IOC to work in a remoting scenario. I have my application server set up to publish Services (SingleCall) which are configured via XML. This works just like this as we all know: RemotingConfiguration.Configure(ConfigFile, true); lets say my service looks like that (pseudocode) public class TourService : ITourService { IRepository _repository; public TourService() { _repository = new SqlServerRepository(); } } But what I rather would like to have sure looks like this: public class TourService : ITourService { IRepository _repository; public TourService(IRepository repository) { _repository = repository; } } On the client side we do something like that (pseudocode again): (ITourService)Activator.GetObject(ITourService, tcp://server/uri); This prompts the server to create a new instance of my TourService class... However this doesn't seem to work out well because the .NET Remoting Infrastructure want's to know the type it should publish but I would rather like to point it to the way how it could retrieve the object it should publish. In other words, route it through the IOC process pipe of - let's say windsor castle - for example. Currently I'm a bit lost on that task...

    Read the article

  • Unity IoC and MVC modelbinding

    - by danielovich
    Is it ok to have a static field in my controller for my modelbinder to call ? Eg. public class AuctionItemsController : Controller { private IRepository<IAuctionItem> GenericAuctionItemRepository; private IAuctionItemRepository AuctionItemRepository; public AuctionItemsController(IRepository<IAuctionItem> genericAuctionItemRepository, IAuctionItemRepository auctionItemRepository) { GenericAuctionItemRepository = genericAuctionItemRepository; AuctionItemRepository = auctionItemRepository; StaticGenericAuctionItemRepository = genericAuctionItemRepository; } internal static IRepository<IAuctionItem> StaticGenericAuctionItemRepository; here is the modelbinder public class AuctionItemModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (AuctionItemsController.StaticGenericAuctionItemRepository != null) { AuctionLogger.LogException(new Exception("controller is null")); } NameValueCollection form = controllerContext.HttpContext.Request.Form; var item = AuctionItemsController.StaticGenericAuctionItemRepository.GetSingle(Convert.ToInt32(controllerContext.RouteData.Values["id"])); item.Description = form["title"]; item.Price = int.Parse(form["price"]); item.Title = form["title"]; item.CreatedDate = DateTime.Now; item.AuctionId = 1; //TODO: Stop hardcoding this item.UserId = 1; return item; }} i am using Unity as IoC and I find it weird to register my modelbinder in the IoC container. Any other good design considerations I shold do ?

    Read the article

  • Is it possible for two VS2008 C# class library projects to share a single namespace?

    - by jeah
    I am trying to share a common namespace between two projects in a single solution. The projects are "Blueprint" and "Repositories". Blueprint contains Interfaces for the entire application and serves as a reference for the application structure. In the Blueprint project, I have an interface with the following declaration: namespace Application.Repositories{ public interface IRepository{ IEntity Get(Guid id); } } In the Repositories project I have a class the following class: namespace Application.Repositories{ public class STDRepository: IRepository { STD Get(Guid id){ return new SkankyExGirlfriendDataContext() .FirstOrDefault<STD>(x=>x.DiseaseId == id); } } } However, this does not work. The Repositories project has a reference to the Blueprint project. I receive a VS error: "The type or namespace name 'IRepository' could not be found (are you missing a using directive or an assembly reference?) - Normally, this is easy to fix but adding a using statement doesn't make sense since they have the same namespace. I tried it anyway and it didn't work. The reference has been added, and without the line of code referencing that interface, both projects compile successfully. I am lost here. I have searched all over and have found nothing, so I am assuming that there is something fundamentally wrong with what I'm doing ... but I don't know what it is. So, I would appreciate some explanation or guidance as to how to fix this problem. I hope you guys can help. Note: The reason I want to do it this way and keep the interfaces under the same namespace is because I want a solid project to keep all the interfaces in, in order to have a reference for the full architecture of the application. I have considered work arounds, such as putting all of the interfaces in the Blueprint.Application namespace instead of the application namespace. However, that would require me to write the using statement on virtually every page in the application...and my fingers get tired. Thanks again guys...

    Read the article

  • What is the purpose of unit testing an interface repository

    - by ahsteele
    I am unit testing an ICustomerRepository interface used for retrieving objects of type Customer. As a unit test what value am I gaining by testing the ICustomerRepository in this manner? Under what conditions would the below test fail? For tests of this nature is it advisable to do tests that I know should fail? i.e. look for id 4 when I know I've only placed 5 in the repository I am probably missing something obvious but it seems the integration tests of the class that implements ICustomerRepository will be of more value. [TestClass] public class CustomerTests : TestClassBase { private Customer SetUpCustomerForRepository() { return new Customer() { CustId = 5, DifId = "55", CustLookupName = "The Dude", LoginList = new[] { new Login { LoginCustId = 5, LoginName = "tdude" }, new Login { LoginCustId = 5, LoginName = "tdude2" } } }; } [TestMethod] public void CanGetCustomerById() { // arrange var customer = SetUpCustomerForRepository(); var repository = Stub<ICustomerRepository>(); // act repository.Stub(rep => rep.GetById(5)).Return(customer); // assert Assert.AreEqual(customer, repository.GetById(5)); } } Test Base Class public class TestClassBase { protected T Stub<T>() where T : class { return MockRepository.GenerateStub<T>(); } } ICustomerRepository and IRepository public interface ICustomerRepository : IRepository<Customer> { IList<Customer> FindCustomers(string q); Customer GetCustomerByDifID(string difId); Customer GetCustomerByLogin(string loginName); } public interface IRepository<T> { void Save(T entity); void Save(List<T> entity); bool Save(T entity, out string message); void Delete(T entity); T GetById(int id); ICollection<T> FindAll(); }

    Read the article

  • Using SimpleDB (with SimpleSavant) with POCO / existing entities, not attributes on my classes

    - by alex
    I'm trying to use Simple Savant within my application, to use SimpleDB I currently have (for example) public class Person { public Guid Id { get; set; } public string Name { get; set; } public string Description { get; set; } public DateTime DateOfBirth { get; set; } } To use this with Simple Savant, i'd have to put attributes above the class declaration, and property - [DomainName("Person")] above the class, and [ItemName] above the Id property. I have all my entities in a seperate assembly. I also have my Data access classes an a seperate assembly, and a class factory selects, based on config, the IRepository (in this case, IRepository I want to be able to use my existing simple class - without having attributes on the properties etc.. In case I switch out of simple db, to something else - then I only need to create a different implementation of IRepository. Should I create a "DTO" type class to map the two together? Is there a better way?

    Read the article

  • Generic Repository with SQLite and SQL Compact Databases

    - by Andrew Petersen
    I am creating a project that has a mobile app (Xamarin.Android) using a SQLite database and a WPF application (Code First Entity Framework 5) using a SQL Compact database. This project will even eventually have a SQL Server database as well. Because of this I am trying to create a generic repository, so that I can pass in the correct context depending on which application is making the request. The issue I ran into is my DataContext for the SQL Compact database inherits from DbContext and the SQLite database inherits from SQLiteConnection. What is the best way to make this generic, so that it doesn't matter what kind of database is on the back end? This is what I have tried so far on the SQL Compact side: public interface IRepository<TEntity> { TEntity Add(TEntity entity); } public class Repository<TEntity, TContext> : IRepository<TEntity>, IDisposable where TEntity : class where TContext : DbContext { private readonly TContext _context; public Repository(DbContext dbContext) { _context = dbContext as TContext; } public virtual TEntity Add(TEntity entity) { return _context.Set<TEntity>().Add(entity); } } And on the SQLite side: public class ElverDatabase : SQLiteConnection { static readonly object Locker = new object(); public ElverDatabase(string path) : base(path) { CreateTable<Ticket>(); } public int Add<T>(T item) where T : IBusinessEntity { lock (Locker) { return Insert(item); } } }

    Read the article

  • How to use the unit of work and repository patterns in a service oriented enviroment

    - by A. Karimi
    I've created an application framework using the unit of work and repository patterns for it's data layer. Data consumer layers such as presentation depend on the data layer design. For example a CRUD abstract form has a dependency to a repository (IRepository). This architecture works like a charm in client/server environments (Ex. a WPF application and a SQL Server). But I'm looking for a good pattern to change or reuse this architecture for a service oriented environment. Of course I have some ideas: Idea 1: The "Adapter" design pattern Keep the current architecture and create a new unit of work and repository implementation which can work with a service instead of the ORM. Data layer consumers are loosely coupled to the data layer so it's possible but the problem is about the unit of work; I have to create a context which tracks the objects state at the client side and sends the changes to the server side on calling the "Commit" (Something that I think the RIA has done for Silverlight). Here the diagram: ----------- CLIENT----------- | ------------------ SERVER ---------------------- [ UI ] -> [ UoW/Repository ] ---> [ Web Services ] -> [ UoW/Repository ] -> [DB] Idea 2: Add another layer Add another layer (let say "local services" or "data provider"), then put it between the data layer (unit of work and repository) and the data consumer layers (like UI). Then I have to rewrite the consumer classes (CRUD and other classes which are dependent to IRepository) to depend on another interface. And the diagram: ----------------- CLIENT ------------------ | ------------------- SERVER --------------------- [ UI ] -> [ Local Services/Data Provider ] ---> [ Web Services ] -> [ UoW/Repository ] -> [DB] Please note that I have the local services layer on the current architecture but it doesn't expose the data layer functionality. In another word the UI layer can communicate with both of the data and local services layers whereas the local services layer also uses the data layer. | | | | | | | | ---> | Local Services | ---> | | | UI | | | | Data | | | | | | | ----------------------------> | |

    Read the article

  • Storing non-content data in Orchard

    - by Bertrand Le Roy
    A CMS like Orchard is, by definition, designed to store content. What differentiates content from other kinds of data is rather subtle. The way I would describe it is by saying that if you would put each instance of a kind of data on its own web page, if it would make sense to add comments to it, or tags, or ratings, then it is content and you can store it in Orchard using all the convenient composition options that it offers. Otherwise, it probably isn't and you can store it using somewhat simpler means that I will now describe. In one of the modules I wrote, Vandelay.ThemePicker, there is some configuration data for the module. That data is not content by the definition I gave above. Let's look at how this data is stored and queried. The configuration data in question is a set of records, each of which has a number of properties: public class SettingsRecord { public virtual int Id { get; set;} public virtual string RuleType { get; set; } public virtual string Name { get; set; } public virtual string Criterion { get; set; } public virtual string Theme { get; set; } public virtual int Priority { get; set; } public virtual string Zone { get; set; } public virtual string Position { get; set; } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Each property has to be virtual for nHibernate to handle it (it creates derived classed that are instrumented in all kinds of ways). We also have an Id property. The way these records will be stored in the database is described from a migration: public int Create() { SchemaBuilder.CreateTable("SettingsRecord", table => table .Column<int>("Id", column => column.PrimaryKey().Identity()) .Column<string>("RuleType", column => column.NotNull().WithDefault("")) .Column<string>("Name", column => column.NotNull().WithDefault("")) .Column<string>("Criterion", column => column.NotNull().WithDefault("")) .Column<string>("Theme", column => column.NotNull().WithDefault("")) .Column<int>("Priority", column => column.NotNull().WithDefault(10)) .Column<string>("Zone", column => column.NotNull().WithDefault("")) .Column<string>("Position", column => column.NotNull().WithDefault("")) ); return 1; } When we enable the feature, the migration will run, which will create the table in the database. Once we've done that, all we have to do in order to use the data is inject an IRepository<SettingsRecord>, which is what I'm doing from the set of helpers I put under the SettingsService class: private readonly IRepository<SettingsRecord> _repository; private readonly ISignals _signals; private readonly ICacheManager _cacheManager; public SettingsService( IRepository<SettingsRecord> repository, ISignals signals, ICacheManager cacheManager) { _repository = repository; _signals = signals; _cacheManager = cacheManager; } The repository has a Table property, which implements IQueryable<SettingsRecord> (enabling all kind of Linq queries) as well as methods such as Delete and Create. Here's for example how I'm getting all the records in the table: _repository.Table.ToList() And here's how I'm deleting a record: _repository.Delete(_repository.Get(r => r.Id == id)); And here's how I'm creating one: _repository.Create(new SettingsRecord { Name = name, RuleType = ruleType, Criterion = criterion, Theme = theme, Priority = priority, Zone = zone, Position = position }); In summary, you create a record class, a migration, and you're in business and can just manipulate the data through the repository that the framework is exposing. You even get ambient transactions from the work context.

    Read the article

  • Building a Repository Pattern against an EF 5 EDMX Model - Part 1

    - by Juan
    I am part of a year long plus project that is re-writing an existing application for a client.  We have decided to develop the project using Visual Studio 2012 and .NET 4.5.  The project will be using a number of technologies and patterns to include Entity Framework 5, WCF Services, and WPF for the client UI.This is my attempt at documenting some of the successes and failures that I will be coming across in the development of the application.In building the data access layer we have to access a database that has already been designed by a dedicated dba. The dba insists on using Stored Procedures which has made the use of EF a little more difficult.  He will not allow direct table access but we did manage to get him to allow us to use Views.  Since EF 5 does not have good support to do Code First with Stored Procedures, my option was to create a model (EDMX) against the existing database views.   I then had to go select each entity and map the Insert/Update/Delete functions to their respective stored procedure. The next step after I had completed mapping the stored procedures to the entities in the EDMX model was to figure out how to build a generic repository that would work well with Entity Framework 5.  After reading the blog posts below, I adopted much of their code with some changes to allow for the use of Ninject for dependency injection.http://www.tcscblog.com/2012/06/22/entity-framework-generic-repository/ http://www.tugberkugurlu.com/archive/generic-repository-pattern-entity-framework-asp-net-mvc-and-unit-testing-triangle IRepository.cs public interface IRepository : IDisposable where T : class { void Add(T entity); void Update(T entity, int id); T GetById(object key); IQueryable Query(Expression> predicate); IQueryable GetAll(); int SaveChanges(); int SaveChanges(bool validateEntities); } GenericRepository.cs public abstract class GenericRepository : IRepository where T : class { public abstract void Add(T entity); public abstract void Update(T entity, int id); public abstract T GetById(object key); public abstract IQueryable Query(Expression> predicate); public abstract IQueryable GetAll(); public int SaveChanges() { return SaveChanges(true); } public abstract int SaveChanges(bool validateEntities); public abstract void Dispose(); } One of the issues I ran into was trying to do an update. I kept receiving errors so I posted a question on Stack Overflow http://stackoverflow.com/questions/12585664/an-object-with-the-same-key-already-exists-in-the-objectstatemanager-the-object and came up with the following hack. If someone has a better way, please let me know. DbContextRepository.cs public class DbContextRepository : GenericRepository where T : class { protected DbContext Context; protected DbSet DbSet; public DbContextRepository(DbContext context) { if (context == null) throw new ArgumentException("context"); Context = context; DbSet = Context.Set(); } public override void Add(T entity) { if (entity == null) throw new ArgumentException("Cannot add a null entity."); DbSet.Add(entity); } public override void Update(T entity, int id) { if (entity == null) throw new ArgumentException("Cannot update a null entity."); var entry = Context.Entry(entity); if (entry.State == EntityState.Detached) { var attachedEntity = DbSet.Find(id); // Need to have access to key if (attachedEntity != null) { var attachedEntry = Context.Entry(attachedEntity); attachedEntry.CurrentValues.SetValues(entity); } else { entry.State = EntityState.Modified; // This should attach entity } } } public override T GetById(object key) { return DbSet.Find(key); } public override IQueryable Query(Expression> predicate) { return DbSet.Where(predicate); } public override IQueryable GetAll() { return Context.Set(); } public override int SaveChanges(bool validateEntities) { Context.Configuration.ValidateOnSaveEnabled = validateEntities; return Context.SaveChanges(); } #region IDisposable implementation public override void Dispose() { if (Context != null) { Context.Dispose(); GC.SuppressFinalize(this); } } #endregion IDisposable implementation } At this point I am able to start creating individual repositories that are needed and add a Unit of Work.  Stay tuned for the next installment in my path to creating a Repository Pattern against EF5.

    Read the article

  • Loosely coupled .NET Cache Provider using Dependency Injection

    - by Rhames
    I have recently been reading the excellent book “Dependency Injection in .NET”, written by Mark Seemann. I do not generally buy software development related books, as I never seem to have the time to read them, but I have found the time to read Mark’s book, and it was time well spent I think. Reading the ideas around Dependency Injection made me realise that the Cache Provider code I wrote about earlier (see http://geekswithblogs.net/Rhames/archive/2011/01/10/using-the-asp.net-cache-to-cache-data-in-a-model.aspx) could be refactored to use Dependency Injection, which should produce cleaner code. The goals are to: Separate the cache provider implementation (using the ASP.NET data cache) from the consumers (loose coupling). This will also mean that the dependency on System.Web for the cache provider does not ripple down into the layers where it is being consumed (such as the domain layer). Provide a decorator pattern to allow a consumer of the cache provider to be implemented separately from the base consumer (i.e. if we have a base repository, we can decorate this with a caching version). Although I used the term repository, in reality the cache consumer could be just about anything. Use constructor injection to provide the Dependency Injection, with a suitable DI container (I use Castle Windsor). The sample code for this post is available on github, https://github.com/RobinHames/CacheProvider.git ICacheProvider In the sample code, the key interface is ICacheProvider, which is in the domain layer. 1: using System; 2: using System.Collections.Generic; 3:   4: namespace CacheDiSample.Domain 5: { 6: public interface ICacheProvider<T> 7: { 8: T Fetch(string key, Func<T> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry); 9: IEnumerable<T> Fetch(string key, Func<IEnumerable<T>> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry); 10: } 11: }   This interface contains two methods to retrieve data from the cache, either as a single instance or as an IEnumerable. the second paramerter is of type Func<T>. This is the method used to retrieve data if nothing is found in the cache. The ASP.NET implementation of the ICacheProvider interface needs to live in a project that has a reference to system.web, typically this will be the root UI project, or it could be a separate project. The key thing is that the domain or data access layers do not need system.web references adding to them. In my sample MVC application, the CacheProvider is implemented in the UI project, in a folder called “CacheProviders”: 1: using System; 2: using System.Collections.Generic; 3: using System.Linq; 4: using System.Web; 5: using System.Web.Caching; 6: using CacheDiSample.Domain; 7:   8: namespace CacheDiSample.CacheProvider 9: { 10: public class CacheProvider<T> : ICacheProvider<T> 11: { 12: public T Fetch(string key, Func<T> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry) 13: { 14: return FetchAndCache<T>(key, retrieveData, absoluteExpiry, relativeExpiry); 15: } 16:   17: public IEnumerable<T> Fetch(string key, Func<IEnumerable<T>> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry) 18: { 19: return FetchAndCache<IEnumerable<T>>(key, retrieveData, absoluteExpiry, relativeExpiry); 20: } 21:   22: #region Helper Methods 23:   24: private U FetchAndCache<U>(string key, Func<U> retrieveData, DateTime? absoluteExpiry, TimeSpan? relativeExpiry) 25: { 26: U value; 27: if (!TryGetValue<U>(key, out value)) 28: { 29: value = retrieveData(); 30: if (!absoluteExpiry.HasValue) 31: absoluteExpiry = Cache.NoAbsoluteExpiration; 32:   33: if (!relativeExpiry.HasValue) 34: relativeExpiry = Cache.NoSlidingExpiration; 35:   36: HttpContext.Current.Cache.Insert(key, value, null, absoluteExpiry.Value, relativeExpiry.Value); 37: } 38: return value; 39: } 40:   41: private bool TryGetValue<U>(string key, out U value) 42: { 43: object cachedValue = HttpContext.Current.Cache.Get(key); 44: if (cachedValue == null) 45: { 46: value = default(U); 47: return false; 48: } 49: else 50: { 51: try 52: { 53: value = (U)cachedValue; 54: return true; 55: } 56: catch 57: { 58: value = default(U); 59: return false; 60: } 61: } 62: } 63:   64: #endregion 65:   66: } 67: }   The FetchAndCache helper method checks if the specified cache key exists, if it does not, the Func<U> retrieveData method is called, and the results are added to the cache. Using Castle Windsor to register the cache provider In the MVC UI project (my application root), Castle Windsor is used to register the CacheProvider implementation, using a Windsor Installer: 1: using Castle.MicroKernel.Registration; 2: using Castle.MicroKernel.SubSystems.Configuration; 3: using Castle.Windsor; 4:   5: using CacheDiSample.Domain; 6: using CacheDiSample.CacheProvider; 7:   8: namespace CacheDiSample.WindsorInstallers 9: { 10: public class CacheInstaller : IWindsorInstaller 11: { 12: public void Install(IWindsorContainer container, IConfigurationStore store) 13: { 14: container.Register( 15: Component.For(typeof(ICacheProvider<>)) 16: .ImplementedBy(typeof(CacheProvider<>)) 17: .LifestyleTransient()); 18: } 19: } 20: }   Note that the cache provider is registered as a open generic type. Consuming a Repository I have an existing couple of repository interfaces defined in my domain layer: IRepository.cs 1: using System; 2: using System.Collections.Generic; 3:   4: using CacheDiSample.Domain.Model; 5:   6: namespace CacheDiSample.Domain.Repositories 7: { 8: public interface IRepository<T> 9: where T : EntityBase 10: { 11: T GetById(int id); 12: IList<T> GetAll(); 13: } 14: }   IBlogRepository.cs 1: using System; 2: using CacheDiSample.Domain.Model; 3:   4: namespace CacheDiSample.Domain.Repositories 5: { 6: public interface IBlogRepository : IRepository<Blog> 7: { 8: Blog GetByName(string name); 9: } 10: }   These two repositories are implemented in the DataAccess layer, using Entity Framework to retrieve data (this is not important though). One important point is that in the BaseRepository implementation of IRepository, the methods are virtual. This will allow the decorator to override them. The BlogRepository is registered in a RepositoriesInstaller, again in the MVC UI project. 1: using Castle.MicroKernel.Registration; 2: using Castle.MicroKernel.SubSystems.Configuration; 3: using Castle.Windsor; 4:   5: using CacheDiSample.Domain.CacheDecorators; 6: using CacheDiSample.Domain.Repositories; 7: using CacheDiSample.DataAccess; 8:   9: namespace CacheDiSample.WindsorInstallers 10: { 11: public class RepositoriesInstaller : IWindsorInstaller 12: { 13: public void Install(IWindsorContainer container, IConfigurationStore store) 14: { 15: container.Register(Component.For<IBlogRepository>() 16: .ImplementedBy<BlogRepository>() 17: .LifestyleTransient() 18: .DependsOn(new 19: { 20: nameOrConnectionString = "BloggingContext" 21: })); 22: } 23: } 24: }   Now I can inject a dependency on the IBlogRepository into a consumer, such as a controller in my sample code: 1: using System; 2: using System.Collections.Generic; 3: using System.Linq; 4: using System.Web; 5: using System.Web.Mvc; 6:   7: using CacheDiSample.Domain.Repositories; 8: using CacheDiSample.Domain.Model; 9:   10: namespace CacheDiSample.Controllers 11: { 12: public class HomeController : Controller 13: { 14: private readonly IBlogRepository blogRepository; 15:   16: public HomeController(IBlogRepository blogRepository) 17: { 18: if (blogRepository == null) 19: throw new ArgumentNullException("blogRepository"); 20:   21: this.blogRepository = blogRepository; 22: } 23:   24: public ActionResult Index() 25: { 26: ViewBag.Message = "Welcome to ASP.NET MVC!"; 27:   28: var blogs = blogRepository.GetAll(); 29:   30: return View(new Models.HomeModel { Blogs = blogs }); 31: } 32:   33: public ActionResult About() 34: { 35: return View(); 36: } 37: } 38: }   Consuming the Cache Provider via a Decorator I used a Decorator pattern to consume the cache provider, this means my repositories follow the open/closed principle, as they do not require any modifications to implement the caching. It also means that my controllers do not have any knowledge of the caching taking place, as the DI container will simply inject the decorator instead of the root implementation of the repository. The first step is to implement a BlogRepository decorator, with the caching logic in it. Note that this can reside in the domain layer, as it does not require any knowledge of the data access methods. BlogRepositoryWithCaching.cs 1: using System; 2: using System.Collections.Generic; 3: using System.Linq; 4: using System.Text; 5:   6: using CacheDiSample.Domain.Model; 7: using CacheDiSample.Domain; 8: using CacheDiSample.Domain.Repositories; 9:   10: namespace CacheDiSample.Domain.CacheDecorators 11: { 12: public class BlogRepositoryWithCaching : IBlogRepository 13: { 14: // The generic cache provider, injected by DI 15: private ICacheProvider<Blog> cacheProvider; 16: // The decorated blog repository, injected by DI 17: private IBlogRepository parentBlogRepository; 18:   19: public BlogRepositoryWithCaching(IBlogRepository parentBlogRepository, ICacheProvider<Blog> cacheProvider) 20: { 21: if (parentBlogRepository == null) 22: throw new ArgumentNullException("parentBlogRepository"); 23:   24: this.parentBlogRepository = parentBlogRepository; 25:   26: if (cacheProvider == null) 27: throw new ArgumentNullException("cacheProvider"); 28:   29: this.cacheProvider = cacheProvider; 30: } 31:   32: public Blog GetByName(string name) 33: { 34: string key = string.Format("CacheDiSample.DataAccess.GetByName.{0}", name); 35: // hard code 5 minute expiry! 36: TimeSpan relativeCacheExpiry = new TimeSpan(0, 5, 0); 37: return cacheProvider.Fetch(key, () => 38: { 39: return parentBlogRepository.GetByName(name); 40: }, 41: null, relativeCacheExpiry); 42: } 43:   44: public Blog GetById(int id) 45: { 46: string key = string.Format("CacheDiSample.DataAccess.GetById.{0}", id); 47:   48: // hard code 5 minute expiry! 49: TimeSpan relativeCacheExpiry = new TimeSpan(0, 5, 0); 50: return cacheProvider.Fetch(key, () => 51: { 52: return parentBlogRepository.GetById(id); 53: }, 54: null, relativeCacheExpiry); 55: } 56:   57: public IList<Blog> GetAll() 58: { 59: string key = string.Format("CacheDiSample.DataAccess.GetAll"); 60:   61: // hard code 5 minute expiry! 62: TimeSpan relativeCacheExpiry = new TimeSpan(0, 5, 0); 63: return cacheProvider.Fetch(key, () => 64: { 65: return parentBlogRepository.GetAll(); 66: }, 67: null, relativeCacheExpiry) 68: .ToList(); 69: } 70: } 71: }   The key things in this caching repository are: I inject into the repository the ICacheProvider<Blog> implementation, via the constructor. This will make the cache provider functionality available to the repository. I inject the parent IBlogRepository implementation (which has the actual data access code), via the constructor. This will allow the methods implemented in the parent to be called if nothing is found in the cache. I override each of the methods implemented in the repository, including those implemented in the generic BaseRepository. Each override of these methods follows the same pattern. It makes a call to the CacheProvider.Fetch method, and passes in the parentBlogRepository implementation of the method as the retrieval method, to be used if nothing is present in the cache. Configuring the Caching Repository in the DI Container The final piece of the jigsaw is to tell Castle Windsor to use the BlogRepositoryWithCaching implementation of IBlogRepository, but to inject the actual Data Access implementation into this decorator. This is easily achieved by modifying the RepositoriesInstaller to use Windsor’s implicit decorator wiring: 1: using Castle.MicroKernel.Registration; 2: using Castle.MicroKernel.SubSystems.Configuration; 3: using Castle.Windsor; 4:   5: using CacheDiSample.Domain.CacheDecorators; 6: using CacheDiSample.Domain.Repositories; 7: using CacheDiSample.DataAccess; 8:   9: namespace CacheDiSample.WindsorInstallers 10: { 11: public class RepositoriesInstaller : IWindsorInstaller 12: { 13: public void Install(IWindsorContainer container, IConfigurationStore store) 14: { 15:   16: // Use Castle Windsor implicit wiring for the block repository decorator 17: // Register the outermost decorator first 18: container.Register(Component.For<IBlogRepository>() 19: .ImplementedBy<BlogRepositoryWithCaching>() 20: .LifestyleTransient()); 21: // Next register the IBlogRepository inmplementation to inject into the outer decorator 22: container.Register(Component.For<IBlogRepository>() 23: .ImplementedBy<BlogRepository>() 24: .LifestyleTransient() 25: .DependsOn(new 26: { 27: nameOrConnectionString = "BloggingContext" 28: })); 29: } 30: } 31: }   This is all that is needed. Now if the consumer of the repository makes a call to the repositories method, it will be routed via the caching mechanism. You can test this by stepping through the code, and seeing that the DataAccess.BlogRepository code is only called if there is no data in the cache, or this has expired. The next step is to add the SQL Cache Dependency support into this pattern, this will be a future post.

    Read the article

  • Handling Model Inheritance in ASP.NET MVC2 & NHibernate

    - by enth
    I've gotten myself stuck on how to handle inheritance in my model when it comes to my controllers/views. Basic Model: public class Procedure : Entity { public Procedure() { } public int Id { get; set; } public DateTime ProcedureDate { get; set; } public ProcedureType Type { get; set; } } public ProcedureA : Procedure { public double VariableA { get; set; } public int VariableB { get; set; } public int Total { get; set; } } public ProcedureB : Procedure { public int Score { get; set; } } etc... many of different procedures eventually. So, I do things like list all the procedures: public class ProcedureController : Controller { public virtual ActionResult List() { IEnumerable<Procedure> procedures = _repository.GetAll(); return View(procedures); } } but now I'm kinda stuck. Basically, from the list page, I need to link to pages where the specific subclass details can be viewed/edited and I'm not sure what the best strategy is. I thought I could add an action on the ProcedureController that would conjure up the right subclass by dynamically figuring out what repository to use and loading the subclass to pass to the view. I had to store the class in the ProcedureType object. I had to create/implement a non-generic IRepository since I can't dynamically cast to a generic one. public virtual ActionResult Details(int procedureID) { Procedure procedure = _repository.GetById(procedureID, false); string className = procedure.Type.Class; Type type = Type.GetType(className, true); Type repositoryType = typeof (IRepository<>).MakeGenericType(type); var repository = (IRepository)DependencyRegistrar.Resolve(repositoryType); Entity procedure = repository.GetById(procedureID, false); return View(procedure); } I haven't even started sorting out how the view is going to determine which partial to load to display the subclass details. I'm wondering if this is a good approach? This makes determining the URL easy. It makes reusing the Procedure display code easy. Another approach is specific controllers for each subclass. It simplifies the controller code, but also means many simple controllers for the many procedure subclasses. Can work out the shared Procedure details with a partial view. How to get to construct the URL to get to the controller/action in the first place? Time to not think about it. Hopefully someone can show me the light. Thanks in advance.

    Read the article

  • MEF part unable to import Autofac autogenerated factory

    - by Michael Wagner
    This is a (to me) pretty weird problem, because it was already running perfectly but went completely south after some unrelated changes. I've got a Repository which imports in its constructor a list of IExtensions via Autofacs MEF integration. One of these extensions contains a backreference to the Repository as Lazy(Of IRepository) (lazy because of the circular reference that would occur). But as soon as I try to use the repository, Autofac throws a ComponentNotRegisteredException with the message "The requested service 'ContractName=Assembly.IRepository()' has not been registered." That is, however, not really correct, because when I break right after the container-build and explore the list of services, it's there - Exported() and with the correct ContractName. I'd appreciate any help on this... Michael

    Read the article

  • Seeding repository Rhino Mocks

    - by ahsteele
    I am embarking upon my first journey of test driven development in C#. To get started I'm using MSTest and Rhino.Mocks. I am attempting to write my first unit tests against my ICustomerRepository. It seems tedious to new up a Customer for each test method. In ruby-on-rails I'd create a seed file and load the customer for each test. It seems logical that I could put this boiler plate Customer into a property of the test class but then I would run the risk of it being modified. What are my options for simplifying this code? [TestMethod] public class CustomerTests : TestClassBase { [TestMethod] public void CanGetCustomerById() { // arrange var customer = new Customer() { CustId = 5, DifId = "55", CustLookupName = "The Dude", LoginList = new[] { new Login { LoginCustId = 5, LoginName = "tdude" } } }; var repository = Stub<ICustomerRepository>(); // act repository.Stub(rep => rep.GetById(5)).Return(customer); // assert Assert.AreEqual(customer, repository.GetById(5)); } [TestMethod] public void CanGetCustomerByDifId() { // arrange var customer = new Customer() { CustId = 5, DifId = "55", CustLookupName = "The Dude", LoginList = new[] { new Login { LoginCustId = 5, LoginName = "tdude" } } }; var repository = Stub<ICustomerRepository>(); // act repository.Stub(rep => rep.GetCustomerByDifID("55")).Return(customer); // assert Assert.AreEqual(customer, repository.GetCustomerByDifID("55")); } [TestMethod] public void CanGetCustomerByLogin() { // arrange var customer = new Customer() { CustId = 5, DifId = "55", CustLookupName = "The Dude", LoginList = new[] { new Login { LoginCustId = 5, LoginName = "tdude" } } }; var repository = Stub<ICustomerRepository>(); // act repository.Stub(rep => rep.GetCustomerByLogin("tdude")).Return(customer); // assert Assert.AreEqual(customer, repository.GetCustomerByLogin("tdude")); } } Test Base Class public class TestClassBase { protected T Stub<T>() where T : class { return MockRepository.GenerateStub<T>(); } } ICustomerRepository and IRepository public interface ICustomerRepository : IRepository<Customer> { IList<Customer> FindCustomers(string q); Customer GetCustomerByDifID(string difId); Customer GetCustomerByLogin(string loginName); } public interface IRepository<T> { void Save(T entity); void Save(List<T> entity); bool Save(T entity, out string message); void Delete(T entity); T GetById(int id); ICollection<T> FindAll(); }

    Read the article

  • Should Factories Persist Entities?

    - by mxmissile
    Should factories persist entities they build? Or is that the job of the caller? Pseudo Example Incoming: public class OrderFactory { public Order Build() { var order = new Order(); .... return order; } } public class OrderController : Controller { public OrderController(IRepository repository) { this.repository = repository; } public ActionResult MyAction() { var order = factory.Build(); repository.Insert(order); ... } } or public class OrderFactory { public OrderFactory(IRepository repository) { this.repository = repository; } public Order Build() { var order = new Order(); ... repository.Insert(order); return order; } } public class OrderController : Controller { public ActionResult MyAction() { var order = factory.Build(); ... } } Is there a recommended practice here?

    Read the article

  • Structuremap Configuration with generics

    - by DarthVader
    I have IRepository interface with which i want to use NHibernateRepository. How do i configure it with structure map? protected void ConfigureDependencies() { ObjectFactory.Initialize( x => { x.For<ILogger>().Use<Logger>(); x.For<IRepository<T>>().Use<NHibernateRepository<T>>(); } ); } I m getting an error on T. Another question I have is if it s OK to make an ApplicationContext static class, configure it with structure map and provide instances with it? I have read that static classes are bad, but I dont want to initialize the ApplicationContext class that I have the injections everywhere. What s the best practice for this? Thanks.

    Read the article

  • Cannot .Count() on IQueryable (NHibernate)

    - by Bruno Reis
    Hello, I'm with an irritating problem. It might be something stupid, but I couldn't find out. I'm using Linq to NHibernate, and I would like to count how many items are there in a repository. Here is a very simplified definition of my repository, with the code that matters: public class Repository { private ISession session; /* ... */ public virtual IQueryable<Product> GetAll() { return session.Linq<Product>(); } } All the relevant code in the end of the question. Then, to count the items on my repository, I do something like: var total = productRepository.GetAll().Count(); The problem is that total is 0. Always. However there are items in the repository. Furthermore, I can .Get(id) any of them. My NHibernate log shows that the following query was executed: SELECT count(*) as y0_ FROM [Product] this_ WHERE not (1=1) That must be that "WHERE not (1=1)" clause the cause of this problem. What can I do to be able .Count() the items in my repository? Thanks! EDIT: Actually the repository.GetAll() code is a little bit different... and that might change something! It is actually a generic repository for Entities. Some of the entities implement also the ILogicalDeletable interface (it contains a single bool property "IsDeleted"). Just before the "return" inside the GetAll() method I check if if the Entity I'm querying implements ILogicalDeletable. public interface IRepository<TEntity, TId> where TEntity : Entity<TEntity, TId> { IQueryable<TEntity> GetAll(); ... } public abstract class Repository<TEntity, TId> : IRepository<TEntity, TId> where TEntity : Entity<TEntity, TId> { public virtual IQueryable<TEntity> GetAll() { if (typeof (ILogicalDeletable).IsAssignableFrom(typeof (TEntity))) { return session.Linq<TEntity>() .Where(x => (x as ILogicalDeletable).IsDeleted == false); } else { return session.Linq<TEntity>(); } } } public interface ILogicalDeletable { bool IsDeleted {get; set;} } public Product : Entity<Product, int>, ILogicalDeletable { ... } public IProductRepository : IRepository<Product, int> {} public ProductRepository : Repository<Product, int>, IProductRepository {} Edit 2: actually the .GetAll() is always returning an empty result-set for entities that implement the ILogicalDeletable interface (ie, it ALWAYS add a WHERE NOT (1=1) clause. I think Linq to NHibernate does not like the typecast.

    Read the article

  • Handling Model Inheritance in ASP.NET MVC2

    - by enth
    I've gotten myself stuck on how to handle inheritance in my model when it comes to my controllers/views. Basic Model: public class Procedure : Entity { public Procedure() { } public int Id { get; set; } public DateTime ProcedureDate { get; set; } public ProcedureType Type { get; set; } } public ProcedureA : Procedure { public double VariableA { get; set; } public int VariableB { get; set; } public int Total { get; set; } } public ProcedureB : Procedure { public int Score { get; set; } } etc... many of different procedures eventually. So, I do things like list all the procedures: public class ProcedureController : Controller { public virtual ActionResult List() { IEnumerable<Procedure> procedures = _repository.GetAll(); return View(procedures); } } but now I'm kinda stuck. Basically, from the list page, I need to link to pages where the specific subclass details can be viewed/edited and I'm not sure what the best strategy is. I thought I could add an action on the ProcedureController that would conjure up the right subclass by dynamically figuring out what repository to use and loading the subclass to pass to the view. I had to store the class in the ProcedureType object. I had to create/implement a non-generic IRepository since I can't dynamically cast to a generic one. public virtual ActionResult Details(int procedureID) { Procedure procedure = _repository.GetById(procedureID, false); string className = procedure.Type.Class; Type type = Type.GetType(className, true); Type repositoryType = typeof (IRepository<>).MakeGenericType(type); var repository = (IRepository)DependencyRegistrar.Resolve(repositoryType); Entity procedure = repository.GetById(procedureID, false); return View(procedure); } I haven't even started sorting out how the view is going to determine which partial to load to display the subclass details. I'm wondering if this is a good approach? This makes determining the URL easy. It makes reusing the Procedure display code easy. Another approach is specific controllers for each subclass. It simplifies the controller code, but also means many simple controllers for the many procedure subclasses. Can work out the shared Procedure details with a partial view. How to get to construct the URL to get to the controller/action in the first place? Time to not think about it. Hopefully someone can show me the light. Thanks in advance.

    Read the article

  • Is There a Real Advantage to Generic Repository?

    - by Sam
    Was reading through some articles on the advantages of creating Generic Repositories for a new app (example). The idea seems nice because it lets me use the same repository to do several things for several different entity types at once: IRepository repo = new EfRepository(); // Would normally pass through IOC into constructor var c1 = new Country() { Name = "United States", CountryCode = "US" }; var c2 = new Country() { Name = "Canada", CountryCode = "CA" }; var c3 = new Country() { Name = "Mexico", CountryCode = "MX" }; var p1 = new Province() { Country = c1, Name = "Alabama", Abbreviation = "AL" }; var p2 = new Province() { Country = c1, Name = "Alaska", Abbreviation = "AK" }; var p3 = new Province() { Country = c2, Name = "Alberta", Abbreviation = "AB" }; repo.Add<Country>(c1); repo.Add<Country>(c2); repo.Add<Country>(c3); repo.Add<Province>(p1); repo.Add<Province>(p2); repo.Add<Province>(p3); repo.Save(); However, the rest of the implementation of the Repository has a heavy reliance on Linq: IQueryable<T> Query(); IList<T> Find(Expression<Func<T,bool>> predicate); T Get(Expression<Func<T,bool>> predicate); T First(Expression<Func<T,bool>> predicate); //... and so on This repository pattern worked fantastic for Entity Framework, and pretty much offered a 1 to 1 mapping of the methods available on DbContext/DbSet. But given the slow uptake of Linq on other data access technologies outside of Entity Framework, what advantage does this provide over working directly with the DbContext? I attempted to write a PetaPoco version of the Repository, but PetaPoco doesn't support Linq Expressions, which makes creating a generic IRepository interface pretty much useless unless you only use it for the basic GetAll, GetById, Add, Update, Delete, and Save methods and utilize it as a base class. Then you have to create specific repositories with specialized methods to handle all the "where" clauses that I could previously pass in as a predicate. Is the Generic Repository pattern useful for anything outside of Entity Framework? If not, why would someone use it at all instead of working directly with Entity Framework? Edit: Original link doesn't reflect the pattern I was using in my sample code. Here is an (updated link).

    Read the article

  • EF Code first + Delete Child Object from Parent?

    - by ebb
    I have a one-to-many relationship between my table Case and my other table CaseReplies. I'm using EF Code First and now wants to delete a CaseReply from a Case object, however it seems impossible to do such thing because it just tries to remove the CaseId from the specific CaseReply record and not the record itself.. short: Case just removes the relationship between itself and the CaseReply.. it does not delete the CaseReply. My code: // Case.cs (Case Object) public class Case { [Key] public int Id { get; set; } public string Topic { get; set; } public string Message { get; set; } public DateTime Date { get; set; } public Guid UserId { get; set; } public virtual User User { get; set; } public virtual ICollection<CaseReply> Replies { get; set; } } // CaseReply.cs (CaseReply Object) public class CaseReply { [Key] public int Id { get; set; } public string Message { get; set; } public DateTime Date { get; set; } public int CaseId { get; set; } public Guid UserId { get; set; } public virtual User User { get; set; } public virtual Case Case { get; set; } } // RepositoryBase.cs public class RepositoryBase<T> : IRepository<T> where T : class { public IDbContext Context { get; private set; } public IDbSet<T> ObjectSet { get; private set; } public RepositoryBase(IDbContext context) { Contract.Requires(context != null); Context = context; if (context != null) { ObjectSet = Context.CreateDbSet<T>(); if (ObjectSet == null) { throw new InvalidOperationException(); } } } public IRepository<T> Remove(T entity) { ObjectSet.Remove(entity); return this; } public IRepository<T> SaveChanges() { Context.SaveChanges(); return this; } } // CaseRepository.cs public class CaseRepository : RepositoryBase<Case>, ICaseRepository { public CaseRepository(IDbContext context) : base(context) { Contract.Requires(context != null); } public bool RemoveCaseReplyFromCase(int caseId, int caseReplyId) { Case caseToRemoveReplyFrom = ObjectSet.Include(x => x.Replies).FirstOrDefault(x => x.Id == caseId); var delete = caseToRemoveReplyFrom.Replies.FirstOrDefault(x => x.Id == caseReplyId); caseToRemoveReplyFrom.Replies.Remove(delete); return Context.SaveChanges() >= 1; } } Thanks in advance.

    Read the article

  • L2S DataContext out of synch: row not found or changed

    - by awrigley
    The Problem I am getting a number of errors that imply that the DataContext, or rather, the way I am using the DataContext is getting out of synch. The error occurs on db.SubmitChanges() where db is my DataContext instance. The error is: Row not found or changed. The problem only occurs intermitently, for example, adding a row then deleting it. If I stop the dev server and restart, the added row is there and I can delete it no problem. Ie, it seems that the problem is related to the DataContext losing track of the rows that have been added. IMPORTANT: Before anyone votes to close this thread, on the basis of it being a duplicate, I have checked the sql server profiler and there is no "Where 0 = 1" in the SQL. I have also recreated the dbml file, so am satisfied that the database schema is in synch with the schema represented by the dbml file. Ie, no cases of mismatched nullable/not nullable columns, etc. My Diagnosis (for what it is worth): It seems to be a problem related to how I am using the DataContext. I am new to MVC, Repositories and Services patterns, so suspect that I have wired things up wrong. The Setup Simple eLearning app in its early stages. Pupils need to be able to add and delete courses (Courses table) to their UserCourses. To do this, I have a service that gets a specific DataContext instance Dependency Injected into its constructor. Service Class Constructor: public class SqlPupilBlockService : IPupilBlockService { DataContext db; public SqlPupilBlockService(DataContext db) { this.db = db; CoursesRepository = new SqlRepository<Course>(db); UserCoursesRepository = new SqlRepository<UserCourse>(db); } // Etc, etc } The CoursesRepository and UserCoursesRepository are both private properties of the service class that are of Type IRepository (just a simple generic repository interface). Sql Respoitory Code: public class SqlRepository<T> : IRepository<T> where T : class { DataContext db; public SqlRepository(DataContext db) { this.db = db; } #region IRepository<T> Members public IQueryable<T> Query { get { return db.GetTable<T>(); } } public List<T> FetchAll() { return Query.ToList(); } public void Add(T entity) { db.GetTable<T>().InsertOnSubmit(entity); } public void Delete(T entity) { db.GetTable<T>().DeleteOnSubmit(entity); } public void Save() { db.SubmitChanges(); } #endregion } The two methods for adding and deleting UserCourses are: Service Methods for Adding and Deleting UserCourses: public void AddUserCourse(int courseId) { UserCourse uc = new UserCourse(); uc.IdCourse = courseId; uc.IdUser = UserId; uc.DateCreated = DateTime.Now; uc.DateAmended = DateTime.Now; uc.Role = "Pupil"; uc.CourseNotes = string.Empty; uc.ActiveStepIndex = 0; UserCoursesRepository.Add(uc); UserCoursesRepository.Save(); } public void DeleteUserCourse(int courseId) { var uc = (UserCoursesRepository.Query.Where(x => x.IdUser == UserId && x.IdCourse == courseId)).Single(); UserCoursesRepository.Delete(uc); UserCoursesRepository.Save(); } Ajax I am using Ajax via Ajax.BeginForm I don't think that is relevant. ASP.NET MVC 3 I am using mvc3, but don't think that is relevant: the errors are related to model code.

    Read the article

< Previous Page | 1 2 3 4 5  | Next Page >