Generic type T as variable name

Im working with EntityFramework and I need some method which will synchronize incoming lists of entities with Database (overwriting records description or mark them as obsolete):

    public void Synchronize<T>(List<T> entityList)
    {
        //do something
    }

First of all I need to get all data from corresponding table and get difference between two lists (one unchangeable thing is entry's GUID). For example if incoming entityList's type is User then I need to get all data from "User" table etc.

It doesn't work:

        var query = from entity in typeof(T)
                    select entity;

Of course I can do it old way:

switch (typeof(T).Name)
        { 
            case "User":
                var query = from user in User
                            select user;
                //Sync with User table
                break;
            case "Project":
                var query = from project in Project 
                            select project ;
                //Sync with Project table
                break;
        }

But maybe there is an elegant way to handle generic? Because I have a plenty of tables to synchronize. Thanks!

Answers


If you have access to the DbContext you could use the method Set<T> to do it.

var query = from entity in context.Set<T>() select entity;

But to make it work in your context you have to put at least a constraint on type T and the entities need to share a type or interface. Otherwise you cannot build your queries, cause T could be anything (object).


Need Your Help

CSS Style sheet not reflecting on my aspx

asp.net css

i have the following CSS style sheet in Site.css

Can I run a stored lambda whose captured values are no longer in scope?

c++ lambda c++-amp

I have a future to which I want to pass a lambda to run when it is complete, but the scope will have changed by the time the lambda executes; what happens to the captured value? For example

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.