.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

Generic Repository in EF4 and MVC

Posted By:      Posted Date: August 27, 2010    Points: 0   Category :ASP.Net


I created a generic repository for a EF4 context in MyProj.Domain.

Now I have services with methods like FindById, FindByUsername that use the repositories.

My controllers use these services. 

Should I do the Mapping from Entities to View Models inside the services or in the controller?

The problem is for example, I might have UserEditViewModel and UserSignInViewModel.

In both cases I would need FindById.

So I might use UserService.FindById(id) in the controller and then map it to UserEditViewModel or UserSignInViewModel.

Or the other way around is to have two methods FindById in the service one returning UserEditViewModel and the other UserSignInViewModel.

I tend to do the mapping in the controller using AutoMapper so it is only a code line but I am not sure if this is the correct way.



View Complete Post

More Related Resource Links

Creating a Generic Entity Framework 4.0 Repository

With .NET 4.0 right around the corner, I thought it would be cool to download Visual Studio 2010 beta 2 and start playing around with the next release of Entity Framework.

The initial release of Entity Framework came with a great deal of criticism. To make matters worse, there was a large uproar when it was rumored that Microsoft would be abandoning LINQ to SQL, in favor of Entity Framework. This was because, at the time, many developers felt Entity Framework was an inferior technology to LINQ to SQL. To set things right, Microsoft proactively moved forward with improving Entity Framework, in time for the 4.0 release of the .NET Framework. This is good news because my initial impressions, so far, have been nothing but positive.

A Generic Dialog ViewModel

I worked on a wpf viewmodel for dialogs, because it seemed strange to me that you needed for instance windows forms dialogs to open or save files in wpf. So I set about creating my own wpf dialogs. After creating the dialog viewmodels there still remained a small issue with the library and also I didn't have much time to write an article about it. I however published the library containing the viewmodels for dialogs with another article on my blog

Format Generic List Bound to Gridview


I have a generic list of a custom type. The custom type has a string and double.

I'm binding the list to a gridview and it outputs everything fine.

I'm trying to format the double column into a currency format. It is in a template field as I'm calculating a running total. I pass the value to a function that returns a double and adds the current value to a running total which I will show in the footer.

The format is not changing to currency as expected when using String.Format("{0:c}", GetTotal(Convert.ToDouble(Eval("Amount"))))

Any ideas on what might be going on and how to fix this?


build repository from SQL 2005? for a Linq, Jquery autocomplete



  I have the a question am going about his correctly I have a database for categories, it has many fields and about 4000 records,  but with a Jquery autocomplete needing speed and the fact that I only need to return a key and category name. I did the following:  (oh just to note, MVC2, Ajax project)


    public class categorySearch
        public Guid Category_GUID { get; set; }
        public string Category_Name { get; set; }


and now for the repository

    public class categoryRepository
        internal List<categorySearch> FindCategory(string searchText, int maxResults)
            List<categorySearch> category = new List<categorySearch>();
            dbWebEntities storedb = new dbWebEntities(); 

            var getcat = storedb.Categories.ToList();

            foreach (var item in getcat)
                category.Add(new categorySearch { Category_GUID = item.Cat_GUID, Category_Name = item.Category_Name});

            var result = from c in category
                         where c.Category_Name.Contains(searchText)
                         orderby c.Category_Name

Need Syntax To Make Results of LINQ Union Return Non-Generic Type



I have the below SQL which works just fine:

SELECT     Message, CreateDate, AccountId, AlertTypeId
FROM       dbo.Alerts
SELECT     TOP (100) PERCENT Status, CreateDate, AccountId,
                          (SELECT     10 AS Expr1) AS AlertTypeId
FROM         dbo.StatusUpdates
WHERE AccountId = PassedInParameter

I have been going about trying to convert the above into a LINQ method and am having problems with return types.
As the above SQL illustrates, I am querying two distinct LINQ tables - Alerts and StatusUpdates -
and then attempting to perform a Union on them. In order to do the union in LINQ, I have to have agreeing types. So, I
am using "var" to make the results of "alerts" and "updates" generic before the union.  

public IList GetStatusUpdatesAsAlertsByAccountId<T>(Int32 accountId)
            using (WorkbookDataContext dc = _conn.GetCont

A generic error occurred in GDI+.



I'm getting this error on the yellow screen and I have no idea what to do with it, or where to start:

[ExternalException (0x80004005): A generic error occurred in GDI+.]
System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams) +377630
NopSolutions.NopCommerce.BusinessLogic.Media.PictureManager.GetPictureUrl(Picture picture, Int32 targetSize, Boolean showDefaultPicture) in F:\Temp\Test\nopCommerce 1.60\Libraries\Nop.BusinessLogic\Media\PictureManager.cs:396
NopSolutions.NopCommerce.BusinessLogic.Media.PictureManager.GetPictureUrl(Picture picture, Int32 targetSize) in F:\Temp\Test\nopCommerce 1.60\Libraries\Nop.BusinessLogic\Media\PictureManager.cs:180
NopSolutions.NopCommerce.Web.Administration.Modules.CategoryInfoControl.BindData() in F:\Temp\Test\nopCommerce 1.60\NopCommerceStore\Administration\Modules\CategoryInfo.ascx.cs:63
NopSolutions.NopCommerce.Web.Administration.Modules.CategoryInfoControl.Page_Load(Object sender, EventArgs e) in F:\Temp\Test\nopCommerce 1.60\NopCommerceStore\Administration\Modules\CategoryInfo.ascx.cs:99
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14

A generic error occurred in GDI+


I am getting this error at this line in my code: ImgThnail.Save(ThumbnailPath, Img.RawFormat);

Here is the entire code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;

    public static class Thumb2
        public static string createThumb(this HttpServerUtility srv, string endPath, string tempPath, int relSize)

            string ThumbnailPath = srv.MapPath("~\\Thumb\\" + endPath);
            string dimensions;
            using (System.Drawing.Image Img = System.Drawing.Image.FromFile(srv.MapPath("~\\" + tempPath))) 
                Size ThumbNailSize = NewImageSize(Img.Height, Img.Width, relSize);
                dimensions = Img.Width.ToString() + " x " + Img.Height.ToString();
                using (System.Drawing.Image ImgThnail = new Bitmap(Img, ThumbNailSize.Width, ThumbNailSize.Height))
                    ImgThnail.Save(ThumbnailPath, Img.RawFormat);
            return dimensions;
        private static Size NewImageSize(int OriginalHeight, int OriginalWidth, double FormatSize)
            Size NewSize;
            double tempval;
            bool landscape;

Basic Instincts: Generic Co- and Contravariance in Visual Basic 2010


Dig into the new co- and contravariance features coming in Visual Studio 2010. Binyam Kelile provides hands-on Visual Basic examples to explain how they provide more flexibility when working with generic interfaces and delegates.

Binyam Kelile

MSDN Magazine March 2010

.NET Matters: Restart Manager and Generic Method Compilation


This month Stephen Toub answers questions pertaining to the Windows Vista Restart Manager API and generic method compilation.

Stephen Toub

MSDN Magazine April 2007

Pure C++: Reflecting on Generic Types


A funny thing happened to templates on their way to the common language runtime (CLR)-they lost their {type} identity. This is analogous to what happens with macros under native programs. Just as the C/C++ compilers have no awareness of macro preprocessor expansions, the CLR has no awareness of template instantiations.

Stanley B. Lippman

MSDN Magazine December 2005

Pure C++: Invoking Generic or Function Templates


As I promised last time, in this month's column I'll walk through the process of defining and invoking a generic or template function under C++\CLI. A function template or a generic function begins with the template or generic keyword followed by its parameter list.

Stanley B. Lippman

MSDN Magazine October 2005

Pure C++: Generic Programming: Template Specialization


As I discussed in my last column, a param-eterized type that does more than simple storage and retrieval is constrained as to the acceptable types that may be safely bound to it (see Pure C++: CLR Generics Versus C++ Templates.

Stanley B. Lippman

MSDN Magazine August 2005

Pure C++: Generic Programming Under .NET


Visual Studio® 2005 brings the type parameter model of generic programming to the Microsoft® . NET Framework. Parameterized types are, of course, standard fare for C++ programmers. So, for those who are unfamiliar with them, I'll give a brief introduction to generic programming in my next few columns.

Stanley B. Lippman

MSDN Magazine April 2005

Advanced Basics: Being Generic Ain't So Bad


Ispeak at a lot of user groups and conferences where I field tech support questions. Recently, a conference attendee (I'll call him Adam) came up to me with a sheaf of printouts, along with the following question.

Ken Getz

MSDN Magazine September 2004

Metadata: Create a Database Schema Repository with Meta Data Services in SQL Server 2000


SQL Server 2000 Meta Data Services is a repository technology that stores and manages metadata for SQL Server. Instead of building database schemas over and over, Meta Data Services allows you to freeze an entire schema for use in other projects. You can also use these schemas for training, testing, or debugging. In this article, the authors will review the various components of Meta Data Services and show how it can be programmed using a Visual Basic client, XML, and XSLT. They will also show you how to manage and manipulate your metadata by generating a simple database schema using a SQL Server repository.

Alok Mehta and Ricardo Rodriguez

MSDN Magazine May 2003

How to Cache System.Collection.Generic.List object


I need to cache System.Collection.Generic.List object with expiration time

var Root = from feed in feedhotel.Descendants(ota + "HotelContent")
                           where (feed.Attribute("HotelCode") != null)
                           select new xmlhotel()




return Root.ToList();

Is it possible to cache Root.ToList() for some time....

Getting generic GDI error when trying to save resized image

Getting following error:A generic error occurred in GDI+.
Any help is appreciated.
Public Sub SaveImageFile(ByVal sourceImage As Bitmap, ByVal saveImagePath As [String], ByVal maxImageWidth As Integer)
            ' Resize if source image width is greater than the max:

            If sourceImage.Width > maxImageWidth Then
                Dim bmp As Bitmap = TryCast(sourceImage, Bitmap)
                Dim newImageHeight As Integer = CInt(Math.Truncate(sourceImage.Height * (CSng(maxImageWidth) / CSng(sourceImage.Width))))
                Dim gr As Graphics = Graphics.FromImage(bmp)

                Dim bmpnew As New Bitmap(maxImageWidth, newImageHeight)
                gr.InterpolationMode = InterpolationMode.HighQualityBicubic

                gr.DrawImage(bmpnew, 0, 0, maxImageWidth, newImageHeight)

                'code to manipulate bmpNew goes here.



ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend