Quantcast
Channel: URF - Unit of Work & (extensible/generic) Repositories Framework
Viewing all 1539 articles
Browse latest View live

Updated Wiki: Home

$
0
0

URF vNext (v3.4): ASP.NET v5 RC Web API and pure HTML5/AngularJS (in full TypeScript v1.5) for the presentation layer (no Razor and MVC Controller),AngularJS v2 Beta, EF 7 as VSCode TypeScript & ASP.NET Project - ETA: Q4 - 2015 (inline w/ ASP.NET v5 release schedule)

This framework (over 35K+ downloads) minimizes the surface area of your ORM technology from disseminating in your application. This framework was deliberately designed to be lightweight, small in footprint size, and non-intimidating to extend and maintain.When we say lightweight we really mean lightweight, when using this framework with the Entity Framework provider there are only 10 classes. This lightweight framework will allow you to elegantly, unobtrusively, and easily patternize your applications and systems with Repository, Unit of Work, and Domain Driven Design. To use Generic Repositories or not? The framework allows the freedom of both, generic repositories and the ability to add in your own domain specific repository methods.

Live demo: longle.azurewebsites.net
Live demo is Continuous Integration & Continuous Deployment Site directly from this CodePlex repository.

Architecture Overview (Sample Northwind Application & Framework)

  1. UI (Presentation) Layer
    • ASP.NET MVC - (Sample app: Northwind.Web)
    • Kendo UI - (Sample app: Northwind.Web)
    • AngularJS - (Sample app: Northwind.Web)
  2. Service and Data Layer
    • Repository Pattern - Framework (Repository.Pattern, Repository.Pattern.Ef6, Northwind.Repository)
    • Unit of Work Pattern - Framework (Repository.Pattern, Repository.Pattern.EF6, Northwind.Repository)
    • Entity Framework
    • Service Pattern - Framework (Service.Pattern, Northwind.Service)
  3. Domain Driven Design (*slated for release v4.0.0)
    • Domain Events
    • *more to come

Technology Stack

Visual Studio 2013, Entity Framework 6, Sql Server 2014 / Sql Azure, Azure WebSite, ASP.NET MVC 5,AngularJS, Kendo UI, Angular Kendo, Web Api 2, OData,Entlib Unity

Subscribe to updates: @LeLong37

Project Sponsor


New Post: Can you give us an example about how to use Explicit loading in URF3.5.5?

$
0
0
Hello
I tried a lot to know how use Explicit loading with URF but I did not success.
if you can help me I'll be thankful.
thank you.

New Post: can you give an example for Models with JsonProperty usage

$
0
0
I modified the T4 templates and use model like

[JsonProperty("id")]
public int Id { get; set; }

I also added ..

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);


when i call webApi .. whats wrong? Please advice

{"$id":"1","Message":"An error has occurred.","ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"$id":"2","Message":"An error has occurred.","ExceptionMessage":"Error while copying content to a stream.","ExceptionType":"System.Net.Http.HttpRequestException","StackTrace":" at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()","InnerException":{"$id":"3","Message":"An error has occurred.","ExceptionMessage":"Could not load file or assembly 'Newtonsoft.Json, Version=7.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)","ExceptionType":"System.IO.FileLoadException","StackTrace":" at System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type)\r\n at System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)\r\n at System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)\r\n at System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg)\r\n at System.Reflection.CustomAttribute.IsCustomAttributeDefined(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, RuntimeType attributeFilterType, Int32 attributeCtorToken, Boolean mustBeInheritable)\r\n at System.Reflection.CustomAttribute.IsDefined(RuntimePropertyInfo property, RuntimeType caType)\r\n at System.Reflection.RuntimePropertyInfo.IsDefined(Type attributeType, Boolean inherit)\r\n at Newtonsoft.Json.Serialization.DefaultContractResolver.GetSerializableMembers(Type objectType)\r\n at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateProperties(Type type, MemberSerialization memberSerialization)\r\n at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateObjectContract(Type objectType)\r\n at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateContract(Type objectType)\r\n at Newtonsoft.Json.Serialization.DefaultContractResolver.ResolveContract(Type type)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)"}}}

Created Unassigned: skip page must be after orderBy [1257]

$
0
0
Hi,
in class Repository<TEntity>:
```
internal IQueryable<TEntity> Select(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
List<Expression<Func<TEntity, object>>> includes = null,
int? page = null,
int? pageSize = null)
{
IQueryable<TEntity> query = _dbSet;

if (includes != null)
{
query = includes.Aggregate(query, (current, include) => current.Include(include));
}
if (orderBy != null)
{
query = orderBy(query);
}
if (filter != null)
{
query = query.AsExpandable().Where(filter);
}
if (page != null && pageSize != null)
{
query = query.Skip((page.Value - 1)*pageSize.Value).Take(pageSize.Value);
}
return query;
}

```
the " if (page != null && pageSize != null)" should be inside the "if (orderBy != null)" clause.
or if the user tries to skip pages without setting the orderBy, a "System.NotSupportedException" exception will occur.

Regards.

Created Unassigned: Adding Collections [1258]

$
0
0
Hi

I am trying to do some experiment with this framework. Query is working fine. Though I am having some discomfort against exposing the entities while using oData. I don't know what are other ways possible to avoid this.

But my mail problem is, while I am trying to create an order object along with its child collection object OrderDetail and trying to insert, I get an error. It says

"The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: A referential integrity constraint violation occurred: The property value(s) of 'Order.OrderID' on one end of a relationship do not match the property value(s) of 'OrderDetail.OrderID' on the other end."

There are no such example to show how to add object and its collection together. Can you please get back?

Many Thanks

New Post: Unable to insert/Update database with UoW

$
0
0
I have downloaded UoW and followed the source code to developed my project. I can query the database with the UoW, but whenever I try to do insert/Update I get this error below but the same code I can use my custom DbContext directly to insert/update.  
System.InvalidOperationException occurred
HResult=-2146233079
Message=The entity type Documents is not part of the model for the current context.
Source=EntityFramework
StackTrace:
   at System.Data.Entity.Internal.InternalContext.UpdateEntitySetMappingsForType(Type entityType)
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
   at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Attach(Object entity)
   at System.Data.Entity.DbSet`1.Attach(TEntity entity)
   at MyProject.Test.DAL.Patterns.Repository`1.Insert(TEntity entity) in c:\Users\admin\Desktop\DocumentProject\MyProject.Test.DAL\Patterns\Repository.cs:line 64
InnerException:
  • Local '_dbSet.Local' threw an exception of type 'System.InvalidOperationException' System.Collections.ObjectModel.ObservableCollection<MyProject.Test.Documents> {System.InvalidOperationException}
Below is the code I am using
{
    #region Private Fields

    private readonly IDataContextAsync _context;
    private readonly DbSet<TEntity> _dbSet;
    private readonly IUnitOfWorkAsync _unitOfWork;

    #endregion Private Fields

    public Repository(IDataContextAsync context, IUnitOfWorkAsync unitOfWork)
    {
        _context = context;
        _unitOfWork = unitOfWork;

        // Temporarily for FakeDbContext, Unit Test and Fakes
        var dbContext = context as DbContext;

        if (dbContext != null)
        {
            _dbSet = dbContext.Set<TEntity>();
        }
        else
        {
            var fakeContext = context as FakeDbContext;

            if (fakeContext != null)
            {
                _dbSet = fakeContext.Set<TEntity>();
            }
        }
    }
Unit of work Constructor

#region Private Fields

    private IDataContextAsync _dataContext;
    private bool _disposed;
    private ObjectContext _objectContext;
    private DbTransaction _transaction;
    private Dictionary<string, dynamic> _repositories;

    #endregion Private Fields

    #region Constuctor/Dispose

    public UnitOfWork(IDataContextAsync dataContext)
    {
        _dataContext = dataContext;
        _repositories = new Dictionary<string, dynamic>();
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    public virtual void Dispose(bool disposing)
    {
        if (_disposed)
            return;

        if (disposing)
        {
            // free other managed objects that implement
            // IDisposable only

            try
            {
                if (_objectContext != null && _objectContext.Connection.State == ConnectionState.Open)
                {
                    _objectContext.Connection.Close();
                }
            }
            catch (ObjectDisposedException)
            {
                // do nothing, the objectContext has already been disposed
            }

            if (_dataContext != null)
            {
                _dataContext.Dispose();
                _dataContext = null;
            }
        }

        // release any unmanaged objects
        // set the object references to null

        _disposed = true;
    }

    #endregion Constuctor/Dispose
Service Pattern

ublic abstract class Service<TEntity> : IService<TEntity> where TEntity : class, IObjectState
{
    #region Private Fields
    private readonly IRepositoryAsync<TEntity> _repository;
    #endregion Private Fields

    #region Constructor
    protected Service(IRepositoryAsync<TEntity> repository) { _repository = repository; }
    #endregion Constructor
//Implementations below//
The Db Context

    public partial class NorthwindContext : DataContext
{
    static NorthwindContext()
    {
        Database.SetInitializer<NorthwindContext>(null);
    }

    public NorthwindContext()
        : base("Name=NorthwindContext")
    {
    }        

    public DbSet<Category> Categories { get; set; }
    public DbSet<CustomerDemographic> CustomerDemographics { get; set; }
    public DbSet<Customer> Customers { get; set; }
    public DbSet<Employee> Employees { get; set; }
    public DbSet<OrderDetail> OrderDetails { get; set; }
    //Other DBsets//

New Post: Unable to insert/Update database with UoW

$
0
0
I have finally figure out my issue. Leaving the Temporarily FakeDbContext was the issue.
        //// Temporarily for FakeDbContext, Unit Test and Fakes
        var dbContext = context as DbContext;

        if (dbContext != null)
        {
            _dbSet = dbContext.Set<TEntity>();
        }
        else
          var fakeContext = context as FakeDbContext;

            if (fakeContext != null)
           {
                _dbSet = fakeContext.Set<TEntity>();
            }
        }

New Post: Implement ASP.Net Identity 2.0 with IdentityDbcontext


New Post: Implement ASP.Net Identity 2.0 with IdentityDbcontext

Updated Wiki: Documentation

$
0
0

Here are the only two (2) requirements to bootstrap your app and integrate with the framework.

  1. All entities are required to implement IObjectState, we've done this through implementing a base entity class (Entity.cs) which are entities inherit (e.g. Customer.cs).
    Note: we use the EF Power Tools from EF Team, and modified the T4 templates to generate our entities to inherit Entity.cs.
  2. Your DbContext is required to inherit from DataContext.cs.
    Note: we use the EF Power Tools and modified the T4 templates so when the DbContext is generated it already inherits DataContext.
  3. It is recommended you download source code and projects and include them directly into your solution so you can make changes as they are needed for your use cases, after all the framework isextremely lightweight, designed to have a very small footprint and has less than 10 classes.

Optional (recommended) Readings

  • Download the source code, (IMPORTANT:) compile and run all the unit and integration tests, almost all implementation questions can be answered by reviewing them e.g. CustomerRepositoryTests.
  • Review integration test e.g. CustomerRepositoryTest.cs, this is the most comprehensive tests and will run against a database, which illustrates most of the core features of the framework. If time permits review the other integration tests as well, this shouldn't take more than 15 minutes.
  • Review CustomerControllers.cs, this illustrates how to leverage the framework in ASP.NET MVC for all typical CRUD like activity.
  • Review UnityConfig.cs, this illustrates DI/IoC configuration of the framework, most importantly Singleton like behavior that the IDataContext that is bound to the lifecycle of an HttpRequest, this is needed regardless of which brand or type of DI/IoC framework you are using.
  • Leverage the lightweight documentation (below), the documentation is indeed very lightweight and that is deliberate, as is the framework as well.The (non-intimidating) framework has an extremely small footprint - 10 total classes, which includes the Entity Framework provider, with this being said a the framework should also only have lightweight set of documentation that is easy, fast to read and understand.

Documentation

v3.3 (docs updated - 12/2/2014)
Adding Custom Repositories
Repeatable Integration Tests with Northwind Test Db & Seed Data
Using Framework in ASP.NET MVC 5 with EF, AngularJS & Kendo UI
Find Object by Primary Key(s)
Inserting & Update (Upsert) / CRUD with a Complex Object Graph with Different States
Deep Loading a Complex Object Graph
Performing Async Selects with Includes and Sorting
Object Graph State(s) while Disconnected or Between different DataContext(s)
Query Against Entity Framework or IQueryable Directly
ASP Identity Integration (thanks toNeilski)


v3.2 (docs updated - 9/23/2014)
Quick CRUD Samples in LINQPad
Transactions, Scope, Commits and Rollbacks
Quick Setup in ASP.NET MVC 5 (Video) Walkthrough
ASP.NET MVC Controller & DI/IoC (DbContext Singleton Behavior Registration)
Services Pattern Example (Business Layer Fascade)
Adding Custom Queries to (Extending the) Repository
Encapsulating Query Logic with the Query Object Pattern (Reusable Queries)
Invoking Stored Procedures with Service Pattern Examples

v2.x (docs updated - 3/12/2014)
Generic Unit of Work & Extensible Repository in ASP.NET MVC & Entity Framework

v1.x (docs updated - 1/7/2014)
Generic Unit of Work and Repository Introduction & Overview

We have rich discussion and issues forums, 9 times out of 10, most of the questions we receive have already been answered in our discussion/issues forums. If not, start a discussion up, we and/or the community will help. Worse case scenario if question(s), issue(s), or implementation needs Live support, we offer this throughCodementor. This should be a last resort, again because the framework is meant to be easily integrated and consumed. This is an option because we have ran into teams that need live assistance, customization, quick bootstrappiing, guidance with architecture or simply have requirements (e.g. enterprise teams) to use a framework that has support.

Guidance and/or Support
Discussions
Issues
Subscribe to Updates


Need another data provider? Implement the interfaces in the Repository.Pattern project! Ideas, features, bugs, or any other contributions? Simply do a pull request and we'll consider making part of the official release.

New Post: Implement ASP.Net Identity 2.0 with IdentityDbcontext

Created Unassigned: Triggers are not executing [1259]

$
0
0
Hi,

Triggers are not executing or fired while updating or inserting the entity.

New Post: Implement ASP.Net Identity 2.0 with IdentityDbcontext

$
0
0
Thank you Neilski. I'm excercising your code. My i ask you what is the and where to use ApplicationUserService?

And btw i have troubleshooting with C#6 features. It wont compile somtimes.

New Post: Implement ASP.Net Identity 2.0 with IdentityDbcontext

$
0
0
Hello, you may not want/need to use the ApplicationUserService, but it is there, and can be extended, if you want to access the ApplicationUser data graph outside of the Identity sub-system. Generally, you would probably not want to do this as it would be easy to corrupt the data that Identity manages directly, but sometimes you may want to. For example, you may want to retrieve a specific view that contains/references the ApplicationUser entity - the ApplicationUserService would be a convenient place to do this - but use with caution!

What compilation errors are you getting?

New Post: Implement ASP.Net Identity 2.0 with IdentityDbcontext

$
0
0
I see. Well, is there any special reason IApplicationRoleService and IApplicationUserService does not inherits from IService<TEntity> but ApplicationUserService and IApplicationRoleService does from Service<TEntity>?

And that Abl projects. Are they your code? What does mean abl?


I didn't note the errors but at $ and => operators generally. Now its compiles. No problem but sometimes all C#6 features gives error. May be its about the my system.

New Post: Implement ASP.Net Identity 2.0 with IdentityDbcontext

$
0
0
You are quite right about the interfaces, I have updated the service interfaces to inherit from IService<> - this is what happens if you rely on ReSharper too much!

The 'Abl' namespace references some class libraries and is derived from my company's name. In this application, the libraries really only provide some general purpose helper functions. Feel free to use them, or replace them with your own.

Let me know if you run across any further compilation issues. String interpolation etc. are C# version 6.0 features, so you may need to re-code these if running in an earlier environment.

New Post: Implement ASP.Net Identity 2.0 with IdentityDbcontext

$
0
0
Thanks for your answers.

I've no problem with C# 6 features. Id googled and found whats wrong.
http://stackoverflow.com/a/31548221/1628636

I was looking for Identity and multi-language works with URF. With your works i found both :) thank you.

:) Now URF + Caching calling you. :)

Thanks for everything Neil, they are very usefull for me.

New Post: Implement ASP.Net Identity 2.0 with IdentityDbcontext

$
0
0
My pleasure - pleased it has been of use.

New Post: Implement ASP.Net Identity 2.0 with IdentityDbcontext

$
0
0
Hi there. Me again. I wanna ask another question.There is a line in Startup.Auth at end of the ApplicationUserManager method like below
            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider<ApplicationUser, Guid>(
                        dataProtectionProvider.Create("UrfIdentity"));
            }
What the UrfIdentity plain text. Is it can be any text or is it depend to something another? Thank you again.

New Post: Implement ASP.Net Identity 2.0 with IdentityDbcontext

$
0
0
The MSDN documentation is a little unclear as to the implications of using different string values. From the published examples, the string is set to "ASP.NET Identity", which is arguably more appropriate.

Other people may have more insight into this argument.
Viewing all 1539 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>