Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get a set of numbers when I call GetType Name in MVC?

I'm using c# Asp.net MVC. I have a TPH model, so I am calling GetType().Name to find out which class type is being used. But sometimes when I call GetType().Name I not only get the name of the model but a large string of numbers after it. Why is this happening how can I avoid this?

example

public string DiscriminatorValue
{
    get{ return this.GetType.Name;
}
//...
RedirectToAction("Index", 
                 "Files", 
                  new { itemId = vm.itemid, 
                        itemtype = vm.item.DiscriminatorValue.ToString()});

and get this:

DiscriminatorActualValue_D808C81C7BDE227500B30C6760AC934EA4A1307BD88500694065B3389D2642B1

like image 859
Bob Avatar asked Feb 15 '23 10:02

Bob


2 Answers

It's because you call the method on a proxy type that was created for you by Entity framework.

You can read about proxies here: http://msdn.microsoft.com/en-us/data/jj592886.aspx and there (at the end) you also have an explanation of how to get the actual type (which solves your issue)

Quote from the link above:

Getting the actual entity type from a proxy type

Proxy types have names that look something like this: System.Data.Entity.DynamicProxies .Blog_5E43C6C196972BF0754973E48C9C941092D86818CD94005E9A759B70BF6E48E6

You can find the entity type for this proxy type using the GetObjectType method from ObjectContext. For example:

using (var context = new BloggingContext())
{
    var blog = context.Blogs.Find(1);
    var entityType = ObjectContext.GetObjectType(blog.GetType());
}
like image 77
Michal B. Avatar answered Feb 17 '23 00:02

Michal B.


Looks like you're using Entity framework. EF performs lazy loading, therefore you might get a proxy, that was generated by EF on the fly.

Solution: When loading your entities, always eagerly load your 'DiscriminatorValue' entities by adding .Include("DiscriminatorValue") to the respective statement.

like image 34
Thomas Weller Avatar answered Feb 17 '23 00:02

Thomas Weller