简体   繁体   中英

C# Accessing an Entity Framework Class with only Type Information

OK, this question is tough for me too explain as I am very new generics and many of the high level features of C#. I am trying to write a method using a generic type that will be used to both instantiate new object of that type and also use the type information to access the correct class in my Entity Framework 5.0 dbContext. What I have does not compile but I believe the code will better explain my problem, as my wording is probably too vague to really explain what I am trying to do.

CODE

public void AddNewRecord<T>() where T : new()  
{    
    T record = new T();  
    _Context.T.Add(record);  //HERE IS MY PROBLEM T would normally be tbl_x
    _BindSource.DataSource = _Context.T.Local.ToBindingList(); //Same goes for here  
}

How can I use T to access a class in my dbcntext?
I am not even sure this is possible. I appreciate any help you guys/gals can offer.

You want to do this:

_Context.Set<T>().Add(record);
_BindingSource.DataSource = _Context.Set<T>().Local.ToBindingList();

I notice that your context is a class member. Be very careful about using a DbContext this way, DbContexts are designed to be short lived, and will get slower and slower and user more and more memory without giving it up if you keep it around for the life of your program.

DbContext does not real memory management, or pruning of its caches because it expects to be destroyed relatively quickly.

This is what you are after:

_Context.Set<T>().Add(record);

Check out here for my full example https://github.com/lukemcgregor/StaticVoid.Repository/blob/master/StaticVoid.Repository.EntityFramework/DbContextRepositoryDataSource.cs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM