Search Results

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

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

  • Fluent NHibernate Many to one mapping

    - by Jit
    I am creating a NHibenate application with one to many relationship. Like City and State data. City table CREATE TABLE [dbo].[State]( [StateId] [varchar](2) NOT NULL primary key, [StateName] [varchar](20) NULL) CREATE TABLE [dbo].[City]( [Id] [int] primary key IDENTITY(1,1) NOT NULL , [State_id] [varchar](2) NULL refrences State(StateId), [CityName] [varchar](50) NULL) My mapping is follows public CityMapping() { Id(x = x.Id); Map(x = x.State_id); Map(x = x.CityName); HasMany(x = x.EmployeePreferedLocations) .Inverse() .Cascade.SaveUpdate() ; References(x = x.State) //.Cascade.All(); //.Class(typeof(State)) //.Not.Nullable() .Cascade.None() .Column("State_id") ; } public StateMapping() { Id(x => x.StateId) .GeneratedBy.Assigned(); Map(x => x.StateName); HasMany(x => x.Jobs) .Inverse(); //.Cascade.SaveUpdate(); HasMany(x => x.EmployeePreferedLocations) .Inverse(); HasMany(x => x.Cities) // .Inverse() .Cascade.SaveUpdate() //.Not.LazyLoad() ; } Models are as follows: [Serializable] public partial class City { public virtual System.String CityName { get; set; } public virtual System.Int32 Id { get; set; } public virtual System.String State_id { get; set; } public virtual IList<EmployeePreferedLocation> EmployeePreferedLocations { get; set; } public virtual JobPortal.Data.Domain.Model.State State { get; set; } public City(){} } public partial class State { public virtual System.String StateId { get; set; } public virtual System.String StateName { get; set; } public virtual IList<City> Cities { get; set; } public virtual IList<EmployeePreferedLocation> EmployeePreferedLocations { get; set; } public virtual IList<Job> Jobs { get; set; } public State() { Cities = new List<City>(); EmployeePreferedLocations = new List<EmployeePreferedLocation>(); Jobs = new List<Job>(); } //public virtual void AddCity(City city) //{ // city.State = this; // Cities.Add(city); //} } My Unit Testing code is below. City city = new City(); IRepository<State> rState = new Repository<State>(); Dictionary<string, string> critetia = new Dictionary<string, string>(); critetia.Add("StateId", "TX"); State frState = rState.GetByCriteria(critetia); city.CityName = "Waco"; city.State = frState; IRepository<City> rCity = new Repository<City>(); rCity.SaveOrUpdate(city); City frCity = rCity.GetById(city.Id); The problem is , I am not able to insert record. The error is below. "Invalid index 2 for this SqlParameterCollection with Count=2." But the error will not come if I comment State_id mapping field in the CityMapping file. I donot know what mistake is I did. If do not give the mapping Map(x = x.State_id); the value of this field is null, which is desired. Please help me how to solve this issue.

    Read the article

  • ASP.NET MVC 3 Hosting :: How to Deploy Web Apps Using ASP.NET MVC 3, Razor and EF Code First - Part I

    - by mbridge
    First, you can download the source code from http://efmvc.codeplex.com. The following frameworks will be used for this step by step tutorial. public class Category {     public int CategoryId { get; set; }     [Required(ErrorMessage = "Name Required")]     [StringLength(25, ErrorMessage = "Must be less than 25 characters")]     public string Name { get; set;}     public string Description { get; set; }     public virtual ICollection<Expense> Expenses { get; set; } } Expense Class public class Expense {             public int ExpenseId { get; set; }            public string  Transaction { get; set; }     public DateTime Date { get; set; }     public double Amount { get; set; }     public int CategoryId { get; set; }     public virtual Category Category { get; set; } }    Define Domain Model Let’s create domain model for our simple web application Category Class We have two domain entities - Category and Expense. A single category contains a list of expense transactions and every expense transaction should have a Category. In this post, we will be focusing on CRUD operations for the entity Category and will be working on the Expense entity with a View Model object in the later post. And the source code for this application will be refactored over time. The above entities are very simple POCO (Plain Old CLR Object) classes and the entity Category is decorated with validation attributes in the System.ComponentModel.DataAnnotations namespace. Now we want to use these entities for defining model objects for the Entity Framework 4. Using the Code First approach of Entity Framework, we can first define the entities by simply writing POCO classes without any coupling with any API or database library. This approach lets you focus on domain model which will enable Domain-Driven Development for applications. EF code first support is currently enabled with a separate API that is runs on top of the Entity Framework 4. EF Code First is reached CTP 5 when I am writing this article. Creating Context Class for Entity Framework We have created our domain model and let’s create a class in order to working with Entity Framework Code First. For this, you have to download EF Code First CTP 5 and add reference to the assembly EntitFramework.dll. You can also use NuGet to download add reference to EEF Code First. public class MyFinanceContext : DbContext {     public MyFinanceContext() : base("MyFinance") { }     public DbSet<Category> Categories { get; set; }     public DbSet<Expense> Expenses { get; set; }         }   The above class MyFinanceContext is derived from DbContext that can connect your model classes to a database. The MyFinanceContext class is mapping our Category and Expense class into database tables Categories and Expenses using DbSet<TEntity> where TEntity is any POCO class. When we are running the application at first time, it will automatically create the database. EF code-first look for a connection string in web.config or app.config that has the same name as the dbcontext class. If it is not find any connection string with the convention, it will automatically create database in local SQL Express database by default and the name of the database will be same name as the dbcontext class. You can also define the name of database in constructor of the the dbcontext class. Unlike NHibernate, we don’t have to use any XML based mapping files or Fluent interface for mapping between our model and database. The model classes of Code First are working on the basis of conventions and we can also use a fluent API to refine our model. The convention for primary key is ‘Id’ or ‘<class name>Id’.  If primary key properties are detected with type ‘int’, ‘long’ or ‘short’, they will automatically registered as identity columns in the database by default. Primary key detection is not case sensitive. We can define our model classes with validation attributes in the System.ComponentModel.DataAnnotations namespace and it automatically enforces validation rules when a model object is updated or saved. Generic Repository for EF Code First We have created model classes and dbcontext class. Now we have to create generic repository pattern for data persistence with EF code first. If you don’t know about the repository pattern, checkout Martin Fowler’s article on Repository Let’s create a generic repository to working with DbContext and DbSet generics. public interface IRepository<T> where T : class     {         void Add(T entity);         void Delete(T entity);         T GetById(long Id);         IEnumerable<T> All();     } RepositoryBasse – Generic Repository class protected MyFinanceContext Database {     get { return database ?? (database = DatabaseFactory.Get()); } } public virtual void Add(T entity) {     dbset.Add(entity);            }        public virtual void Delete(T entity) {     dbset.Remove(entity); }   public virtual T GetById(long id) {     return dbset.Find(id); }   public virtual IEnumerable<T> All() {     return dbset.ToList(); } } DatabaseFactory class public class DatabaseFactory : Disposable, IDatabaseFactory {     private MyFinanceContext database;     public MyFinanceContext Get()     {         return database ?? (database = new MyFinanceContext());     }     protected override void DisposeCore()     {         if (database != null)             database.Dispose();     } } Unit of Work If you are new to Unit of Work pattern, checkout Fowler’s article on Unit of Work . According to Martin Fowler, the Unit of Work pattern "maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems." Let’s create a class for handling Unit of Work public interface IUnitOfWork {     void Commit(); } UniOfWork class public class UnitOfWork : IUnitOfWork {     private readonly IDatabaseFactory databaseFactory;     private MyFinanceContext dataContext;       public UnitOfWork(IDatabaseFactory databaseFactory)     {         this.databaseFactory = databaseFactory;     }       protected MyFinanceContext DataContext     {         get { return dataContext ?? (dataContext = databaseFactory.Get()); }     }       public void Commit()     {         DataContext.Commit();     } } The Commit method of the UnitOfWork will call the commit method of MyFinanceContext class and it will execute the SaveChanges method of DbContext class.   Repository class for Category In this post, we will be focusing on the persistence against Category entity and will working on other entities in later post. Let’s create a repository for handling CRUD operations for Category using derive from a generic Repository RepositoryBase<T>. public class CategoryRepository: RepositoryBase<Category>, ICategoryRepository     {     public CategoryRepository(IDatabaseFactory databaseFactory)         : base(databaseFactory)         {         }                } public interface ICategoryRepository : IRepository<Category> { } If we need additional methods than generic repository for the Category, we can define in the CategoryRepository. Dependency Injection using Unity 2.0 If you are new to Inversion of Control/ Dependency Injection or Unity, please have a look on my articles at http://weblogs.asp.net/shijuvarghese/archive/tags/IoC/default.aspx. I want to create a custom lifetime manager for Unity to store container in the current HttpContext. public class HttpContextLifetimeManager<T> : LifetimeManager, IDisposable {     public override object GetValue()     {         return HttpContext.Current.Items[typeof(T).AssemblyQualifiedName];     }     public override void RemoveValue()     {         HttpContext.Current.Items.Remove(typeof(T).AssemblyQualifiedName);     }     public override void SetValue(object newValue)     {         HttpContext.Current.Items[typeof(T).AssemblyQualifiedName] = newValue;     }     public void Dispose()     {         RemoveValue();     } } Let’s create controller factory for Unity in the ASP.NET MVC 3 application.                 404, String.Format(                     "The controller for path '{0}' could not be found" +     "or it does not implement IController.",                 reqContext.HttpContext.Request.Path));       if (!typeof(IController).IsAssignableFrom(controllerType))         throw new ArgumentException(                 string.Format(                     "Type requested is not a controller: {0}",                     controllerType.Name),                     "controllerType");     try     {         controller= container.Resolve(controllerType) as IController;     }     catch (Exception ex)     {         throw new InvalidOperationException(String.Format(                                 "Error resolving controller {0}",                                 controllerType.Name), ex);     }     return controller; }   } Configure contract and concrete types in Unity Let’s configure our contract and concrete types in Unity for resolving our dependencies. private void ConfigureUnity() {     //Create UnityContainer               IUnityContainer container = new UnityContainer()                 .RegisterType<IDatabaseFactory, DatabaseFactory>(new HttpContextLifetimeManager<IDatabaseFactory>())     .RegisterType<IUnitOfWork, UnitOfWork>(new HttpContextLifetimeManager<IUnitOfWork>())     .RegisterType<ICategoryRepository, CategoryRepository>(new HttpContextLifetimeManager<ICategoryRepository>());                 //Set container for Controller Factory                ControllerBuilder.Current.SetControllerFactory(             new UnityControllerFactory(container)); } In the above ConfigureUnity method, we are registering our types onto Unity container with custom lifetime manager HttpContextLifetimeManager. Let’s call ConfigureUnity method in the Global.asax.cs for set controller factory for Unity and configuring the types with Unity. protected void Application_Start() {     AreaRegistration.RegisterAllAreas();     RegisterGlobalFilters(GlobalFilters.Filters);     RegisterRoutes(RouteTable.Routes);     ConfigureUnity(); } Developing web application using ASP.NET MVC 3 We have created our domain model for our web application and also have created repositories and configured dependencies with Unity container. Now we have to create controller classes and views for doing CRUD operations against the Category entity. Let’s create controller class for Category Category Controller public class CategoryController : Controller {     private readonly ICategoryRepository categoryRepository;     private readonly IUnitOfWork unitOfWork;           public CategoryController(ICategoryRepository categoryRepository, IUnitOfWork unitOfWork)     {         this.categoryRepository = categoryRepository;         this.unitOfWork = unitOfWork;     }       public ActionResult Index()     {         var categories = categoryRepository.All();         return View(categories);     }     [HttpGet]     public ActionResult Edit(int id)     {         var category = categoryRepository.GetById(id);         return View(category);     }       [HttpPost]     public ActionResult Edit(int id, FormCollection collection)     {         var category = categoryRepository.GetById(id);         if (TryUpdateModel(category))         {             unitOfWork.Commit();             return RedirectToAction("Index");         }         else return View(category);                 }       [HttpGet]     public ActionResult Create()     {         var category = new Category();         return View(category);     }           [HttpPost]     public ActionResult Create(Category category)     {         if (!ModelState.IsValid)         {             return View("Create", category);         }                     categoryRepository.Add(category);         unitOfWork.Commit();         return RedirectToAction("Index");     }       [HttpPost]     public ActionResult Delete(int  id)     {         var category = categoryRepository.GetById(id);         categoryRepository.Delete(category);         unitOfWork.Commit();         var categories = categoryRepository.All();         return PartialView("CategoryList", categories);       }        } Creating Views in Razor Now we are going to create views in Razor for our ASP.NET MVC 3 application.  Let’s create a partial view CategoryList.cshtml for listing category information and providing link for Edit and Delete operations. CategoryList.cshtml @using MyFinance.Helpers; @using MyFinance.Domain; @model IEnumerable<Category>      <table>         <tr>         <th>Actions</th>         <th>Name</th>          <th>Description</th>         </tr>     @foreach (var item in Model) {             <tr>             <td>                 @Html.ActionLink("Edit", "Edit",new { id = item.CategoryId })                 @Ajax.ActionLink("Delete", "Delete", new { id = item.CategoryId }, new AjaxOptions { Confirm = "Delete Expense?", HttpMethod = "Post", UpdateTargetId = "divCategoryList" })                           </td>             <td>                 @item.Name             </td>             <td>                 @item.Description             </td>         </tr>         }       </table>     <p>         @Html.ActionLink("Create New", "Create")     </p> The delete link is providing Ajax functionality using the Ajax.ActionLink. This will call an Ajax request for Delete action method in the CategoryCotroller class. In the Delete action method, it will return Partial View CategoryList after deleting the record. We are using CategoryList view for the Ajax functionality and also for Index view using for displaying list of category information. Let’s create Index view using partial view CategoryList  Index.chtml @model IEnumerable<MyFinance.Domain.Category> @{     ViewBag.Title = "Index"; }    <h2>Category List</h2>    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>    <div id="divCategoryList">               @Html.Partial("CategoryList", Model) </div> We can call the partial views using Html.Partial helper method. Now we are going to create View pages for insert and update functionality for the Category. Both view pages are sharing common user interface for entering the category information. So I want to create an EditorTemplate for the Category information. We have to create the EditorTemplate with the same name of entity object so that we can refer it on view pages using @Html.EditorFor(model => model) . So let’s create template with name Category. Category.cshtml @model MyFinance.Domain.Category <div class="editor-label"> @Html.LabelFor(model => model.Name) </div> <div class="editor-field"> @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> <div class="editor-label"> @Html.LabelFor(model => model.Description) </div> <div class="editor-field"> @Html.EditorFor(model => model.Description) @Html.ValidationMessageFor(model => model.Description) </div> Let’s create view page for insert Category information @model MyFinance.Domain.Category   @{     ViewBag.Title = "Save"; }   <h2>Create</h2>   <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>   @using (Html.BeginForm()) {     @Html.ValidationSummary(true)     <fieldset>         <legend>Category</legend>                @Html.EditorFor(model => model)               <p>             <input type="submit" value="Create" />         </p>     </fieldset> }   <div>     @Html.ActionLink("Back to List", "Index") </div> ViewStart file In Razor views, we can add a file named _viewstart.cshtml in the views directory  and this will be shared among the all views with in the Views directory. The below code in the _viewstart.cshtml, sets the Layout page for every Views in the Views folder.     @{     Layout = "~/Views/Shared/_Layout.cshtml"; } Tomorrow, we will cotinue the second part of this article. :)

    Read the article

  • Using a Generic Repository pattern with fluent nHibernate

    - by alex
    I'm currently developing a medium sized application, which will access 2 or more SQL databases, on different sites etc... I am considering using something similar to this: http://mikehadlow.blogspot.com/2008/03/using-irepository-pattern-with-linq-to.html However, I want to use fluent nHibernate, in place of Linq-to-SQL (and of course nHibernate.Linq) Is this viable? How would I go about configuring this? Where would my mapping definitions go etc...? This application will eventually have many facets - from a WebUI, WCF Library and Windows applications / services. Also, for example on a "product" table, would I create a "ProductManager" class, that has methods like: GetProduct, GetAllProducts etc... Any pointers are greatly received.

    Read the article

  • Multi tenancy with Unity

    - by Savvas Sopiadis
    Hi everybody! I'm trying to implement this scenario using Unity and i can't figure out how this could be done: the same web application (ASP.NET MVC) should be made accessible to more than one client (multi-tenant). The URL of the web site will differentiate the client (this i know how to get). So getting the URL one could set the (let's call it) IConnectionStringProvider parameter (which will be afterward injected into IRepository and so on). Through which mechanism (using Unity) do i set the IConnectionStringProvider parameter at run time? I have done this in the past using Windsor & IHandlerSelector (see this) but it's my first attempt using Unity. Any help is deeply appreciated! Thanks in advance

    Read the article

  • Mocking User.Identity in ASP.NET MVC

    - by Trey Carroll
    I need to create Unit Tests for an ASP.NET MVC 2.0 web site. The site uses Windows Authentication. I've been reading up on the necessity to mock the HTTP context for code that deals with the HttpContext. I feel like I'm starting to get a handle on the DI pattern as well. (Give the class an attribute of type IRepository and then pass in a Repository object when you instantiate the controller.) What I don't understand, however, is the proper way to Mock the Windows Principal object available through User.Identity. Is this part of the HttpContext? Does any body have a link to an article that demonstrates this (or a recommendation for a book)? Thanks, Trey Carroll

    Read the article

  • Calling generic method in spring.net application context

    - by Bert Vandamme
    Hi, I'm trying to invoke this method in spring.net, but i'm having trouble getting the configuration right. Method: public void AddRepository(IRepository repository) where TEntity : IEntity { Repositories.Add(repository.GetType().Name, repository); } Config: <object type="Spring.Objects.Factory.Config.MethodInvokingFactoryObject, Spring.Core"> <property name="TargetObject"> <ref local="RepositoryFactory" /> </property> <property name="TargetMethod" value="AddRepository"/> <property name="Arguments"> <list> <ref object="BinaryAssetFileRepository"/> </list> </property> </object>" Is it possible to address generic methods in this way? Thx, Bert

    Read the article

  • structuremap configuration change based on settings in app.config

    - by user74825
    I am using structuremap in my project. To inject different implementation of a repository, I want to have a switch in app.config which changes all real implementation of a repository to a mock repositories. Lets say IRepository has two implementations RealRepository and MockRepository ForRequestedType() .TheDefaultIsConcreteType(); I want to have a switch in app.config / web.config say (Mock=1), which changes all real repositories implementation to ForRequestedType() .TheDefaultIsConcreteType(); I don't want to write whole plugin definition in app.config, just want one switch, how do I implement this?

    Read the article

  • First time unit testing (in silverlight)

    - by Jakob
    Hi I've searched some other posts, but most of them assumed that people knew what they were doing in their unit testing, and frankly I don't. I see the idea behind unit testing, and I'm coding an silverlight application much in the blind right now, and I'd like to write some unit tests to kind of be sure I'm on the right path. I'd like to be able to use the SL4 vs 2010 silverlight unit test project template, to keep it simple and not use external tools. So what I need an answer for are questions like: what are the methods of unit testing? what are the differences between unit tests, and automated unit tests? How do I meaningfully unit test in silverlight? What should I be aware of while unit testing (in silverlight) ? Also should I implement some kind of IRepository pattern in my silverlight app to make unit testing easier?

    Read the article

  • Use delegate for Projection in Linq to SQL

    - by Redeemed1
    I have code something like this in an IRepository implementation in Linq to Sql: var newlist = from h in list where h.StringProp1 == "1" select new MyBusinessBO{ firstProp = h.StringProp1, secondProp = h.StringProp2 }; The projection into MyBusinessBO is not difificult but when the Business Object has many properties the projection code becomes very lengthy. Also, as the projection can occur in several places in the Repository we break the DRY principle. Is there any way to abstract out the projection or replace it with a delegate? I.e. replace the code firstProp = h.StringProp1, secondProp = h.StringProp2 with something reusable?

    Read the article

  • How do I get property injection working in Ninject for a ValidationAttribute in MVC?

    - by jaltiere
    I have a validation attribute set up where I need to hit the database to accomplish the validation. I tried setting up property injection the same way I do elsewhere in the project but it's not working. What step am I missing? public class ApplicationIDValidAttribute : ValidationAttribute { [Inject] protected IRepository<MyType> MyRepo; public override bool IsValid(object value) { if (value == null) return true; int id; if (!Int32.TryParse(value.ToString(), out id)) return false; // MyRepo is null here and is never injected var obj= MyRepo.LoadById(id); return (obj!= null); } One other thing to point out, I have the Ninject kernel set up to inject non-public properties, so I don't think that is the problem. I'm using Ninject 2, MVC 2, and the MVC 2 version of Ninject.Web.MVC. Thanks!

    Read the article

  • How to invoke a method with a generic return type using reflection

    - by Andre Luus
    Hi there! I'm trying to invoke a method with reflection that has a generic return type, like this: public class SomeClass<T> { public List<T> GetStuff(); } I get an instance of SomeClass with a call to a Repository's GetClass<T> generic method. MethodInfo lGetSomeClassMethodInfo = typeof(IRepository) .GetMethod("GetClass") .MakeGenericMethod(typeof(SomeClass<>); object lSomeClassInstance = lGetSomeClassMethodInfo.Invoke( lRepositoryInstance, null); After that, I this is where I try to invoke the GetStuff method: typeof(SomeClass<>).GetMethod("GetStuff").Invoke(lSomeClassInstance, null) I get an exception about the fact that the method has generic arguments. However, I can't use MakeGenericMethod to resolve the return type. Also, if instead of typeof(SomeClass<>) I use lSomeClassInstance.GetType() (which should have resolved types) GetMethod("GetStuff") returns null! UPDATE I have found the solution and will post the answer shortly.

    Read the article

  • Partially Modifying an XML serialized document.

    - by Stacey
    I have an XML document, several actually, that will be editable via a front-end UI. I've discovered a problem with this approach (other than the fact that it is using xml files instead of a database... but I cannot change that right now). If one user makes a change while another user is in the process of making a change, then the second one's changes will overwrite the first. I need to be able to request objects from the xml files, change them, and then submit the changes back to the xml file without re-writing the entire file. I've got my entire xml access class posted here (which was formed thanks to wonderful help from stackoverflow!) using System; using System.Linq; using System.Collections; using System.Collections.Generic; namespace Repositories { /// <summary> /// A file base repository represents a data backing that is stored in an .xml file. /// </summary> public partial class Repository<T> : IRepository { /// <summary> /// Default constructor for a file repository /// </summary> public Repository() { } /// <summary> /// Initialize a basic repository with a filename. This will have to be passed from a context to be mapped. /// </summary> /// <param name="filename"></param> public Repository(string filename) { FileName = filename; } /// <summary> /// Discovers a single item from this repository. /// </summary> /// <typeparam name="TItem">The type of item to recover.</typeparam> /// <typeparam name="TCollection">The collection the item belongs to.</typeparam> /// <param name="expression"></param> /// <returns></returns> public TItem Single<TItem, TCollection>(Predicate<TItem> expression) where TCollection : IDisposable, IEnumerable<TItem> { using (var list = List<TCollection>()) { return list.Single(i => expression(i)); } } /// <summary> /// Discovers a collection from the repository, /// </summary> /// <typeparam name="TCollection"></typeparam> /// <returns></returns> public TCollection List<TCollection>() where TCollection : IDisposable { using (var list = System.Xml.Serializer.Deserialize<TCollection>(FileName)) { return (TCollection)list; } } /// <summary> /// Discovers a single item from this repository. /// </summary> /// <typeparam name="TItem">The type of item to recover.</typeparam> /// <typeparam name="TCollection">The collection the item belongs to.</typeparam> /// <param name="expression"></param> /// <returns></returns> public List<TItem> Select<TItem, TCollection>(Predicate<TItem> expression) where TCollection : IDisposable, IEnumerable<TItem> { using (var list = List<TCollection>()) { return list.Where( i => expression(i) ).ToList<TItem>(); } } /// <summary> /// Attempts to save an entire collection. /// </summary> /// <typeparam name="TCollection"></typeparam> /// <param name="collection"></param> /// <returns></returns> public Boolean Save<TCollection>(TCollection collection) { try { // load the collection into an xml reader and try to serialize it. System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument(); xDoc.LoadXml(System.Xml.Serializer.Serialize<TCollection>(collection)); // attempt to flush the file xDoc.Save(FileName); // assume success return true; } catch { return false; } } internal string FileName { get; private set; } } public interface IRepository { TItem Single<TItem, TCollection>(Predicate<TItem> expression) where TCollection : IDisposable, IEnumerable<TItem>; TCollection List<TCollection>() where TCollection : IDisposable; List<TItem> Select<TItem, TCollection>(Predicate<TItem> expression) where TCollection : IDisposable, IEnumerable<TItem>; Boolean Save<TCollection>(TCollection collection); } }

    Read the article

  • Hibernate / MySQL Bulk insert problem

    - by Marty Pitt
    I'm having trouble getting Hibernate to perform a bulk insert on MySQL. I'm using Hibernate 3.3 and MySQL 5.1 At a high level, this is what's happening: @Transactional public Set<Long> doUpdate(Project project, IRepository externalSource) { List<IEntity> entities = externalSource.loadEntites(); buildEntities(entities, project); persistEntities(project); } public void persistEntities(Project project) { projectDAO.update(project); } This results in n log entries (1 for every row) as follows: Hibernate: insert into ProjectEntity (name, parent_id, path, project_id, state, type) values (?, ?, ?, ?, ?, ?) I'd like to see this get batched, so the update is more performant. It's possible that this routine could result in tens-of-thousands of rows generated, and a db trip per row is a killer. Why isn't this getting batched? (It's my understanding that batch inserts are supposed to be default where appropriate by hibernate).

    Read the article

  • How do I set up Array/List dependencies in code with Castle Windsor?

    - by SharePoint Newbie
    Hi, I have the following classes: class Repository : IRepository class ReadOnlyRepository : Repository abstract class Command abstract CommandImpl : Command { public CommandImpl(Repository repository){} } class Service { public Service (Command[] commands){} } I register them in code as follows: var container = new Container("WindsorCOntainer.config"); var container = new WindsorContainer(new XmlInterpreter("WindsorConfig.xml")); container.Kernel.Resolver.AddSubResolver(new ArrayResolver(container.Kernel)); container.AddComponent("repository", typeof(RentServiceRepository)); container.Resolve<RentServiceRepository>(); container.AddComponent("command", typeof(COmmandImpl)); container.AddComponent("rentService", typeof (RentService)); container.Resolve<RentService>(); // Fails here I get the message that "RentService is waiting for dependency commands" What am I doing wrong? Thanks,

    Read the article

  • Windsor + NHibernate + ISession + MVC

    - by dbones
    Hi I am trying to get Windsor to give me an instance ISession for each request, which should be injected into all the repositories Here is my container setup container.AddFacility<FactorySupportFacility>().Register( Component.For<ISessionFactory>().Instance(NHibernateHelper.GetSessionFactory()).LifeStyle.Singleton, Component.For<ISession>().LifeStyle.Transient .UsingFactoryMethod(kernel => kernel.Resolve<ISessionFactory>().OpenSession()) ); //add to the container container.Register( Component.For<IActionInvoker>().ImplementedBy<WindsorActionInvoker>(), Component.For(typeof(IRepository<>)).ImplementedBy(typeof(NHibernateRepository<>)) ); Its based upon a StructureMap post here http://www.kevinwilliampang.com/2010/04/06/setting-up-asp-net-mvc-with-fluent-nhibernate-and-structuremap/ however, when this is run, a new Session is created for every object it is injected too. what am I missing? thanks in advanced (FYI the NHibernateHelper, sets up the config for Nhib)

    Read the article

  • Class design question (Disposable and singleton behavior)

    - by user137348
    The Repository class has singleton behavior and the _db implements the disposable pattern. As excepted the _db object gets disposed after the first call and because of the singleton behavior any other call of _db will crash. [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] public class Repository : IRepository { private readonly DataBase _db; public Repository(DataBase db) { _db = db; } public int GetCount() { using(_db) { return _db.Menus.Count(); } } public Item GetItem(int id) { using(_db) { return _db.Menus.FirstOrDefault(x=>x.Id == id); } } } My question is, is there any way to design this class to work properly without removing the singleton behavior? The Repositoryclass will be serving big amount of requests.

    Read the article

  • StructureMap DI on Model Assembly

    - by Dan dot net
    I’m new to Dependency Injection and had a question/need guidance. I had an application that used the repository pattern for data access. I used StructureMap to get the correct repository and all worked well. I have since broken out my model (including the repository logic) into its own assembly and added a service layer. In the interest of DI the service layer class takes an IRepository in its constructor. This seems wrong to me as now all consumers of my model need to know about the repository (at least configure their DI to know which one to use). I feel like that is getting into the guts of the model. What sounds wrong with this?

    Read the article

  • Developing web apps using ASP.NET MVC 3, Razor and EF Code First - Part 1

    - by shiju
    In this post, I will demonstrate web application development using ASP. NET MVC 3, Razor and EF code First. This post will also cover Dependency Injection using Unity 2.0 and generic Repository and Unit of Work for EF Code First. The following frameworks will be used for this step by step tutorial. ASP.NET MVC 3 EF Code First CTP 5 Unity 2.0 Define Domain Model Let’s create domain model for our simple web application Category class public class Category {     public int CategoryId { get; set; }     [Required(ErrorMessage = "Name Required")]     [StringLength(25, ErrorMessage = "Must be less than 25 characters")]     public string Name { get; set;}     public string Description { get; set; }     public virtual ICollection<Expense> Expenses { get; set; } }   Expense class public class Expense {             public int ExpenseId { get; set; }            public string  Transaction { get; set; }     public DateTime Date { get; set; }     public double Amount { get; set; }     public int CategoryId { get; set; }     public virtual Category Category { get; set; } } We have two domain entities - Category and Expense. A single category contains a list of expense transactions and every expense transaction should have a Category. In this post, we will be focusing on CRUD operations for the entity Category and will be working on the Expense entity with a View Model object in the later post. And the source code for this application will be refactored over time. The above entities are very simple POCO (Plain Old CLR Object) classes and the entity Category is decorated with validation attributes in the System.ComponentModel.DataAnnotations namespace. Now we want to use these entities for defining model objects for the Entity Framework 4. Using the Code First approach of Entity Framework, we can first define the entities by simply writing POCO classes without any coupling with any API or database library. This approach lets you focus on domain model which will enable Domain-Driven Development for applications. EF code first support is currently enabled with a separate API that is runs on top of the Entity Framework 4. EF Code First is reached CTP 5 when I am writing this article. Creating Context Class for Entity Framework We have created our domain model and let’s create a class in order to working with Entity Framework Code First. For this, you have to download EF Code First CTP 5 and add reference to the assembly EntitFramework.dll. You can also use NuGet to download add reference to EEF Code First.    public class MyFinanceContext : DbContext {     public MyFinanceContext() : base("MyFinance") { }     public DbSet<Category> Categories { get; set; }     public DbSet<Expense> Expenses { get; set; }         }   The above class MyFinanceContext is derived from DbContext that can connect your model classes to a database. The MyFinanceContext class is mapping our Category and Expense class into database tables Categories and Expenses using DbSet<TEntity> where TEntity is any POCO class. When we are running the application at first time, it will automatically create the database. EF code-first look for a connection string in web.config or app.config that has the same name as the dbcontext class. If it is not find any connection string with the convention, it will automatically create database in local SQL Express database by default and the name of the database will be same name as the dbcontext class. You can also define the name of database in constructor of the the dbcontext class. Unlike NHibernate, we don’t have to use any XML based mapping files or Fluent interface for mapping between our model and database. The model classes of Code First are working on the basis of conventions and we can also use a fluent API to refine our model. The convention for primary key is ‘Id’ or ‘<class name>Id’.  If primary key properties are detected with type ‘int’, ‘long’ or ‘short’, they will automatically registered as identity columns in the database by default. Primary key detection is not case sensitive. We can define our model classes with validation attributes in the System.ComponentModel.DataAnnotations namespace and it automatically enforces validation rules when a model object is updated or saved. Generic Repository for EF Code First We have created model classes and dbcontext class. Now we have to create generic repository pattern for data persistence with EF code first. If you don’t know about the repository pattern, checkout Martin Fowler’s article on Repository Let’s create a generic repository to working with DbContext and DbSet generics. public interface IRepository<T> where T : class     {         void Add(T entity);         void Delete(T entity);         T GetById(long Id);         IEnumerable<T> All();     }   RepositoryBasse – Generic Repository class public abstract class RepositoryBase<T> where T : class { private MyFinanceContext database; private readonly IDbSet<T> dbset; protected RepositoryBase(IDatabaseFactory databaseFactory) {     DatabaseFactory = databaseFactory;     dbset = Database.Set<T>(); }   protected IDatabaseFactory DatabaseFactory {     get; private set; }   protected MyFinanceContext Database {     get { return database ?? (database = DatabaseFactory.Get()); } } public virtual void Add(T entity) {     dbset.Add(entity);            }        public virtual void Delete(T entity) {     dbset.Remove(entity); }   public virtual T GetById(long id) {     return dbset.Find(id); }   public virtual IEnumerable<T> All() {     return dbset.ToList(); } }   DatabaseFactory class public class DatabaseFactory : Disposable, IDatabaseFactory {     private MyFinanceContext database;     public MyFinanceContext Get()     {         return database ?? (database = new MyFinanceContext());     }     protected override void DisposeCore()     {         if (database != null)             database.Dispose();     } } Unit of Work If you are new to Unit of Work pattern, checkout Fowler’s article on Unit of Work . According to Martin Fowler, the Unit of Work pattern "maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems." Let’s create a class for handling Unit of Work   public interface IUnitOfWork {     void Commit(); }   UniOfWork class public class UnitOfWork : IUnitOfWork {     private readonly IDatabaseFactory databaseFactory;     private MyFinanceContext dataContext;       public UnitOfWork(IDatabaseFactory databaseFactory)     {         this.databaseFactory = databaseFactory;     }       protected MyFinanceContext DataContext     {         get { return dataContext ?? (dataContext = databaseFactory.Get()); }     }       public void Commit()     {         DataContext.Commit();     } }   The Commit method of the UnitOfWork will call the commit method of MyFinanceContext class and it will execute the SaveChanges method of DbContext class.   Repository class for Category In this post, we will be focusing on the persistence against Category entity and will working on other entities in later post. Let’s create a repository for handling CRUD operations for Category using derive from a generic Repository RepositoryBase<T>.   public class CategoryRepository: RepositoryBase<Category>, ICategoryRepository     {     public CategoryRepository(IDatabaseFactory databaseFactory)         : base(databaseFactory)         {         }                } public interface ICategoryRepository : IRepository<Category> { } If we need additional methods than generic repository for the Category, we can define in the CategoryRepository. Dependency Injection using Unity 2.0 If you are new to Inversion of Control/ Dependency Injection or Unity, please have a look on my articles at http://weblogs.asp.net/shijuvarghese/archive/tags/IoC/default.aspx. I want to create a custom lifetime manager for Unity to store container in the current HttpContext.   public class HttpContextLifetimeManager<T> : LifetimeManager, IDisposable {     public override object GetValue()     {         return HttpContext.Current.Items[typeof(T).AssemblyQualifiedName];     }     public override void RemoveValue()     {         HttpContext.Current.Items.Remove(typeof(T).AssemblyQualifiedName);     }     public override void SetValue(object newValue)     {         HttpContext.Current.Items[typeof(T).AssemblyQualifiedName] = newValue;     }     public void Dispose()     {         RemoveValue();     } }   Let’s create controller factory for Unity in the ASP.NET MVC 3 application. public class UnityControllerFactory : DefaultControllerFactory { IUnityContainer container; public UnityControllerFactory(IUnityContainer container) {     this.container = container; } protected override IController GetControllerInstance(RequestContext reqContext, Type controllerType) {     IController controller;     if (controllerType == null)         throw new HttpException(                 404, String.Format(                     "The controller for path '{0}' could not be found" +     "or it does not implement IController.",                 reqContext.HttpContext.Request.Path));       if (!typeof(IController).IsAssignableFrom(controllerType))         throw new ArgumentException(                 string.Format(                     "Type requested is not a controller: {0}",                     controllerType.Name),                     "controllerType");     try     {         controller= container.Resolve(controllerType) as IController;     }     catch (Exception ex)     {         throw new InvalidOperationException(String.Format(                                 "Error resolving controller {0}",                                 controllerType.Name), ex);     }     return controller; }   }   Configure contract and concrete types in Unity Let’s configure our contract and concrete types in Unity for resolving our dependencies.   private void ConfigureUnity() {     //Create UnityContainer               IUnityContainer container = new UnityContainer()                 .RegisterType<IDatabaseFactory, DatabaseFactory>(new HttpContextLifetimeManager<IDatabaseFactory>())     .RegisterType<IUnitOfWork, UnitOfWork>(new HttpContextLifetimeManager<IUnitOfWork>())     .RegisterType<ICategoryRepository, CategoryRepository>(new HttpContextLifetimeManager<ICategoryRepository>());                 //Set container for Controller Factory                ControllerBuilder.Current.SetControllerFactory(             new UnityControllerFactory(container)); }   In the above ConfigureUnity method, we are registering our types onto Unity container with custom lifetime manager HttpContextLifetimeManager. Let’s call ConfigureUnity method in the Global.asax.cs for set controller factory for Unity and configuring the types with Unity.   protected void Application_Start() {     AreaRegistration.RegisterAllAreas();     RegisterGlobalFilters(GlobalFilters.Filters);     RegisterRoutes(RouteTable.Routes);     ConfigureUnity(); }   Developing web application using ASP.NET MVC 3 We have created our domain model for our web application and also have created repositories and configured dependencies with Unity container. Now we have to create controller classes and views for doing CRUD operations against the Category entity. Let’s create controller class for Category Category Controller   public class CategoryController : Controller {     private readonly ICategoryRepository categoryRepository;     private readonly IUnitOfWork unitOfWork;           public CategoryController(ICategoryRepository categoryRepository, IUnitOfWork unitOfWork)     {         this.categoryRepository = categoryRepository;         this.unitOfWork = unitOfWork;     }       public ActionResult Index()     {         var categories = categoryRepository.All();         return View(categories);     }     [HttpGet]     public ActionResult Edit(int id)     {         var category = categoryRepository.GetById(id);         return View(category);     }       [HttpPost]     public ActionResult Edit(int id, FormCollection collection)     {         var category = categoryRepository.GetById(id);         if (TryUpdateModel(category))         {             unitOfWork.Commit();             return RedirectToAction("Index");         }         else return View(category);                 }       [HttpGet]     public ActionResult Create()     {         var category = new Category();         return View(category);     }           [HttpPost]     public ActionResult Create(Category category)     {         if (!ModelState.IsValid)         {             return View("Create", category);         }                     categoryRepository.Add(category);         unitOfWork.Commit();         return RedirectToAction("Index");     }       [HttpPost]     public ActionResult Delete(int  id)     {         var category = categoryRepository.GetById(id);         categoryRepository.Delete(category);         unitOfWork.Commit();         var categories = categoryRepository.All();         return PartialView("CategoryList", categories);       }        }   Creating Views in Razor Now we are going to create views in Razor for our ASP.NET MVC 3 application.  Let’s create a partial view CategoryList.cshtml for listing category information and providing link for Edit and Delete operations. CategoryList.cshtml @using MyFinance.Helpers; @using MyFinance.Domain; @model IEnumerable<Category>      <table>         <tr>         <th>Actions</th>         <th>Name</th>          <th>Description</th>         </tr>     @foreach (var item in Model) {             <tr>             <td>                 @Html.ActionLink("Edit", "Edit",new { id = item.CategoryId })                 @Ajax.ActionLink("Delete", "Delete", new { id = item.CategoryId }, new AjaxOptions { Confirm = "Delete Expense?", HttpMethod = "Post", UpdateTargetId = "divCategoryList" })                           </td>             <td>                 @item.Name             </td>             <td>                 @item.Description             </td>         </tr>          }       </table>     <p>         @Html.ActionLink("Create New", "Create")     </p> The delete link is providing Ajax functionality using the Ajax.ActionLink. This will call an Ajax request for Delete action method in the CategoryCotroller class. In the Delete action method, it will return Partial View CategoryList after deleting the record. We are using CategoryList view for the Ajax functionality and also for Index view using for displaying list of category information. Let’s create Index view using partial view CategoryList  Index.chtml @model IEnumerable<MyFinance.Domain.Category> @{     ViewBag.Title = "Index"; }    <h2>Category List</h2>    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>    <div id="divCategoryList">               @Html.Partial("CategoryList", Model) </div>   We can call the partial views using Html.Partial helper method. Now we are going to create View pages for insert and update functionality for the Category. Both view pages are sharing common user interface for entering the category information. So I want to create an EditorTemplate for the Category information. We have to create the EditorTemplate with the same name of entity object so that we can refer it on view pages using @Html.EditorFor(model => model) . So let’s create template with name Category. Let’s create view page for insert Category information   @model MyFinance.Domain.Category   @{     ViewBag.Title = "Save"; }   <h2>Create</h2>   <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>   @using (Html.BeginForm()) {     @Html.ValidationSummary(true)     <fieldset>         <legend>Category</legend>                @Html.EditorFor(model => model)               <p>             <input type="submit" value="Create" />         </p>     </fieldset> }   <div>     @Html.ActionLink("Back to List", "Index") </div> ViewStart file In Razor views, we can add a file named _viewstart.cshtml in the views directory  and this will be shared among the all views with in the Views directory. The below code in the _viewstart.cshtml, sets the Layout page for every Views in the Views folder.      @{     Layout = "~/Views/Shared/_Layout.cshtml"; }   Source Code You can download the source code from http://efmvc.codeplex.com/ . The source will be refactored on over time.   Summary In this post, we have created a simple web application using ASP.NET MVC 3 and EF Code First. We have discussed on technologies and practices such as ASP.NET MVC 3, Razor, EF Code First, Unity 2, generic Repository and Unit of Work. In my later posts, I will modify the application and will be discussed on more things. Stay tuned to my blog  for more posts on step by step application building.

    Read the article

  • how to update child records when updating the Master table using Linq [closed]

    - by user20358
    I currently use a general repositry class that can update only a single table like so public abstract class MyRepository<T> : IRepository<T> where T : class { protected IObjectSet<T> _objectSet; protected ObjectContext _context; public MyRepository(ObjectContext Context) { _objectSet = Context.CreateObjectSet<T>(); _context = Context; } public IQueryable<T> GetAll() { return _objectSet.AsQueryable(); } public IQueryable<T> Find(Expression<Func<T, bool>> filter) { return _objectSet.Where(filter); } public void Add(T entity) { _objectSet.AddObject(entity); _context.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Added); _context.SaveChanges(); } public void Update(T entity) { _context.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Modified); _context.SaveChanges(); } public void Delete(T entity) { _objectSet.Attach(entity); _context.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Deleted); _objectSet.DeleteObject(entity); _context.SaveChanges(); } } For every table class generated by my EDMX designer I create another class like this public class CustomerRepo : MyRepository<Customer> { public CustomerRepo (ObjectContext context) : base(context) { } } for any updates that I need to make to a particular table I do this: Customer CustomerObj = new Customer(); CustomerObj.Prop1 = ... CustomerObj.Prop2 = ... CustomerObj.Prop3 = ... CustomerRepo.Update(CustomerObj); This works perfectly well when I am updating just to the specific table called Customer. Now if I need to also update each row of another table which is a child of Customer called Orders what changes do I need to make to the class MyRepository. Orders table will have multiple records for a Customer record and multiple fields too, say for example Field1, Field2, Field3. So my questions are: 1.) If I only need to update Field1 of the Orders table for some rows based on a condition and Field2 for some other rows based on a different condition then what changes I need to do? 2.) If there is no such condition and all child rows need to be updated with the same value for all rows then what changes do I need to do? Thanks for taking the time. Look forward to your inputs...

    Read the article

  • Webforms MVP Passive View - event handling

    - by ss2k
    Should the view have nothing event specific in its interface and call the presenter plain methods to handle events and not have any official EventHandlers? For instance // ASPX protected void OnSaveButtonClicked(object sender, EventArgs e) { _Presenter.OnSave(); } Or should the view have event EventHandlers defined in its interface and link those up explicitly to control events on the page // View public interface IView { ... event EventHandler Saved; ... } // ASPX Page implementing the view protected override void OnInit(EventArgs e) { base.OnInit(e); SaveButton.Click += delegate { Saved(this, e); }; } // Presenter internal Presenter(IView view,IRepository repository) { _view = view; _repository = repository; view.Saved += Save; } The second seems like a whole lot of plumbing code to add all over. My intention is to understand the benefits of each style and not just a blanket answer of which to use. My main goals is clarity and high value testability. Testability overall is important, but I wouldn't sacrifice design simplicity and clarity to be able to add another type of test that doesn't lead to too much gain over the test cases already possible with a simpler design. If a design choice does off more testability please include an example (pseudo code is fine) of the type of test it can now offer so I can make my decision if I value that type of extra test enough. Thanks!

    Read the article

  • ASP.Net Entity Framework Repository & Linq

    - by Chris Klepeis
    My scenario: This is an ASP.NET 4.0 web app programmed via C# I implement a repository pattern. My repositorys all share the same ObjectContext, which is stored in httpContext.Items. Each repository creates a new ObjectSet of type E. Heres some code from my repository: public class Repository<E> : IRepository<E>, IDisposable where E : class { private DataModelContainer _context = ContextHelper<DataModelContainer>.GetCurrentContext(); private IObjectSet<E> _objectSet; private IObjectSet<E> objectSet { get { if (_objectSet == null) { _objectSet = this._context.CreateObjectSet<E>(); } return _objectSet; } } public IQueryable<E> GetQuery() { return objectSet; } Lets say I have 2 repositorys, 1 for states and 1 for countrys and want to create a linq query against both. Note that I use POCO classes with the entity framework. State and Country are 2 of these POCO classes. Repository stateRepo = new Repository<State>(); Repository countryRepo = new Repository<Country>(); IEnumerable<State> states = (from s in _stateRepo.GetQuery() join c in _countryRepo.GetQuery() on s.countryID equals c.countryID select s).ToList(); Debug.WriteLine(states.First().Country.country) essentially, I want to retrieve the state and the related country entity. The query only returns the state data... and I get a null argument exception on the Debug.WriteLine LazyLoading is disabled in my .edmx... thats the way I want it.

    Read the article

  • How can I write a clean Repository without exposing IQueryable to the rest of my application?

    - by Simucal
    So, I've read all the Q&A's here on SO regarding the subject of whether or not to expose IQueryable to the rest of your project or not (see here, and here), and I've ultimately decided that I don't want to expose IQueryable to anything but my Model. Because IQueryable is tied to certain persistence implementations I don't like the idea of locking myself into this. Similarly, I'm not sure how good I feel about classes further down the call chain modifying the actual query that aren't in the repository. So, does anyone have any suggestions for how to write a clean and concise Repository without doing this? One problem I see, is my Repository will blow up from a ton of methods for various things I need to filter my query off of. Having a bunch of: IEnumerable GetProductsSinceDate(DateTime date); IEnumberable GetProductsByName(string name); IEnumberable GetProductsByID(int ID); If I was allowing IQueryable to be passed around I could easily have a generic repository that looked like: public interface IRepository<T> where T : class { T GetById(int id); IQueryable<T> GetAll(); void InsertOnSubmit(T entity); void DeleteOnSubmit(T entity); void SubmitChanges(); } However, if you aren't using IQueryable then methods like GetAll() aren't really practical since lazy evaluation won't be taking place down the line. I don't want to return 10,000 records only to use 10 of them later. What is the answer here? In Conery's MVC Storefront he created another layer called the "Service" layer which received IQueryable results from the respository and was responsible for applying various filters. Is this what I should do, or something similar? Have my repository return IQueryable but restrict access to it by hiding it behind a bunch of filter classes like GetProductByName, which will return a concrete type like IList or IEnumerable?

    Read the article

  • Why is ExecuteFunction method only available through base.ExecuteFunction in a child class of Object

    - by Matt
    I'm trying to call ObjectContext.ExecuteFunction from my objectcontext object in the repository of my site. The repository is generic, so all I have is an ObjectContext object, rather than one that actually represents my specific one from the Entity Framework. Here's an example of code that was generated that uses the ExecuteFunction method: [global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")] public global::System.Data.Objects.ObjectResult<ArtistSearchVariation> FindSearchVariation(string source) { global::System.Data.Objects.ObjectParameter sourceParameter; if ((source != null)) { sourceParameter = new global::System.Data.Objects.ObjectParameter("Source", source); } else { sourceParameter = new global::System.Data.Objects.ObjectParameter("Source", typeof(string)); } return base.ExecuteFunction<ArtistSearchVariation>("FindSearchVariation", sourceParameter); } But what I would like to do is something like this... public class Repository<E, C> : IRepository<E, C>, IDisposable where E : EntityObject where C : ObjectContext { private readonly C _ctx; // ... public ObjectResult<E> ExecuteFunction(string functionName, params[]) { // Create object parameters return _ctx.ExecuteFunction<E>(functionName, /* parameters */) } } Anyone know why I have to call ExecuteFunction from base instead of _ctx? Also, is there any way to do something like I've written out? I would really like to keep my repository generic, but with having to execute stored procedures it's looking more and more difficult... Thanks, Matt

    Read the article

  • Validation without ServiceLocator

    - by Dmitriy Nagirnyak
    Hi, I am getting back again and again to it thinking about the best way to perform validation on POCO objects that need access to some context (ISession in NH, IRepository for example). The only option I still can see is to use S*ervice Locator*, so my validation would look like: public User : ICanValidate { public User() {} // We need this constructor (so no context known) public virtual string Username { get; set; } public IEnumerable<ValidationError> Validate() { if (ServiceLocator.GetService<IUserRepository>().FindUserByUsername(Username) != null) yield return new ValidationError("Username", "User already exists.") } } I already use Inversion Of control and Dependency Injection and really don't like the ServiceLocator due to number of facts: Harder to maintain implicit dependencies. Harder to test the code. Potential threading issues. Explicit dependency only on the ServiceLocator. The code becomes harder to understand. Need to register the ServiceLocator interfaces during the testing. But on the other side, with plain POCO objects, I do not see any other way of performing the validation like above without ServiceLocator and only using IoC/DI. So the question would be: is there any way to use DI/IoC for the situation described above? Thanks, Dmitriy.

    Read the article

  • Injecting Subsonic SimpleRepository class to controller

    - by ryudice
    Hi, I'm tryingot get started with IoC, I have an MVC project in which is use subsonic, I'm trying to inject subsonic simplerepository to my controllers but I'm getting this error: StructureMap Exception Code: 205 Missing requested Instance property "connectionStringName" for InstanceKey "60b735fb-0a7f-4eb4-be04-635f6f32233d" Here is my registry class: public class RepositoryRegistry : Registry { protected override void configure() { ForRequestedType<IRepository>().TheDefault.Is.OfConcreteType(typeof(SimpleRepository)); } } And here is my controller factory: public class StoreControllerFactory: DefaultControllerFactory { protected override IController GetControllerInstance(Type controllerType) { IController result = null; if (controllerType!=null) { result = ObjectFactory.GetInstance(controllerType) as Controller; } return result; } } And this is how I configure StructureMap: protected void Application_Start() { RegisterRoutes(RouteTable.Routes); ObjectFactory.Initialize(x=> { x.AddRegistry(new RepositoryRegistry()); }); ControllerBuilder.Current.SetControllerFactory(new StoreControllerFactory()); var sparkSettings = new SparkSettings().SetDebug(true).AddNamespace("System.Web.Mvc.Html"); ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new SparkViewFactory(sparkSettings)); } Any help would be appreciated! Thanks!

    Read the article

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