Create reference to a class from a string variable [duplicate] - c#

This question already has answers here:
C# Reflection: How to get class reference from string?
(6 answers)
Closed 7 years ago.
Here is what I need to do;
string className = "Customer";
List<className> myList = new List<className>();
className can be any of my Entity Framework classes. I have used Customer just as an example.
I hope this is possible. If so, how?
UPDATE:
I also need to use this approach for retrieving data from an Entity Framework dbContext. For example...
string className = "Customer";
var myData = db.Set<className>();
Sorry. Not sure if I should have created another question here or updated this one. Be gentle with me. I'm new here. :o)

If you want you can use reflection in this case, but I would think over another solution.
Type type = Type.GetType("Namespace.ClassName");
Type listType = typeof(List<>).MakeGenericType(new [] { type } );
IList list = (IList)Activator.CreateInstance(listType);

You can use:
Type customerType = Type.GetType("this.is.a.namespace.Customer");
Related: other question

Related

c# Anonymous type. How to use datatype name as member name [duplicate]

This question already has an answer here:
How do I use a C# keyword as a property name?
(1 answer)
Closed 2 months ago.
I have to create a json query dynamically where one of the properties is called "bool". I need this name because the system I send the requests to, expects this naming.
To create the json I use C# anonymous types like:
var myquery = new { bool = "Yes" };
but I'm not allowed to use bool as member name. Is there a fix for that somehow?
I have searched for a solution, without any success. I hope there is an easy fix.
Yes, you put the # character in front of the variable.
var myquery = new { #bool = "Yes" };
You can prefix it with an #.
var myquery = new { #bool = "Yes" };

Class that is member of another class is always null [duplicate]

This question already has answers here:
Load child entity on the fetch of the Parent entity EFCore
(3 answers)
Why EF navigation property return null?
(7 answers)
Closed 2 years ago.
I am working on a C# WPF project using Entity Framework code first.
I have a class that has an instance of another class as its member. I am trying to access the value of a property of the member class. I can get the value this way:
var com = context.MyParentClass.Where(p => (p.Identity == id)).Select(c =>
new
{
id = c.Identity,
PropertyValue = c.MyChildClass.PropertyValue
}
);
foreach(var item in com)
{
string xx = item.PropertyValue;
MessageBox.Show(xx);
}
But when I try to get the value without the select, the member class is always null:
var com = db.MyParentClass.SingleOrDefault(b => b.Identity == id);
string xx = com.MyChildClass.PropertyValue; //MyChildClass is null
MessageBox.Show(xx);
Does anyone know what is going on here? How do I get around the null-problem?
You have to make sure that lazy loading is enabled or not.
context.Configuration.ProxyCreationEnabled should be true.
context.Configuration.LazyLoadingEnabled should be true.
Navigation property should be defined as public, virtual. The
context will NOT do lazy loading if the property is not defined as
virtual.
You can use Include for eager loading also. Thank you #CodeCaster for the suggestion.
Reference: https://www.entityframeworktutorial.net/lazyloading-in-entity-framework.aspx

sort list using property variable [duplicate]

This question already has answers here:
How can I do an OrderBy with a dynamic string parameter?
(11 answers)
Closed 7 years ago.
Suppose I have this list of process or any other object
List<Process> listProcess = new List<Process>();
I can sort it using this line listProcess.OrderBy(p => p.Id);
But what if I have only string name of property obtained in runtime. I assume, I should use reflection to get the property object. Can I use orderby method or I should use Sort and then pass own comparer?
You can have a look at the post referred in the comment. Or, you can achieve that using simple reflection like this
var sortedList = list.OrderBy(o => o.GetType().GetProperty(propName).GetValue(o));
Where
List<object> list; //a list of any object(s)
string propName; //name of the property to be used in OrderBy

Difference between new ClassName and new ClassName() in entity framewrok query [duplicate]

This question already has answers here:
Why are C# 3.0 object initializer constructor parentheses optional?
(5 answers)
Closed 7 years ago.
I trying to get some values from database by using entity framework
i have a doubt about
Difference between new ClassName and new ClassName() in entity framewrok query
Code 1
dbContext.StatusTypes.Select(s => new StatusTypeModel() { StatusTypeId =
s.StatusTypeId, StatusTypeName = s.StatusTypeName }).ToList();
Code 2
dbContext.StatusTypes.Select(s => new StatusTypeModel { StatusTypeId =
s.StatusTypeId, StatusTypeName = s.StatusTypeName }).ToList();
You can see the changes from where i create a new StatusTypeModel and new StatusTypeModel() object.
The both queries are working for me. but i don't know the differences between of code 1 and code 2 .
This has nothing to do with EF. This is a C# language feature. When you declare properties of a class using { ... } you don't need to tell that the empty constructor of a class shall be called. Example:
new StatusTypeModel() { StatusTypeId = s.StatusTypeId, ... }
is exactly the same like this:
new StatusTypeModel { StatusTypeId = s.StatusTypeId, ... }
There is no difference in performance. The generated IL (intermediate language) is identical.
However, if you don't declare properties you must call the constructor like this:
var x = new StatusTypeModel(); // brackets are mandatory
x.StatusTypeId = s.StatusTypeId;
...

what kind of property names can i have ? [duplicate]

This question already has answers here:
.NET valid property names
(4 answers)
Closed 8 years ago.
can we have property names like $ref #schema ? If so, how ? If not why not ?
I am actually to do something like this
dynamic d = new ExpandoObject();
d.$ref = somevlaue;
but I can't do that?
Also , how do I workaround the fact that keywords can't be property names?
Use
public string #class {get; set;}
for using keywords as variable names. For more information you can see the rules for Identifiers.
Since you are mainly interested in the ExpandoObject, a workaround would be to directly set and/or retrieve those property names by casting the ExpandoObject to an IDictionary<string, Object>:
dynamic d = new ExpandoObject();
var dict = (IDictionary<string, Object>)d;
dict["$ref"] = "haha!";
The language has the guideline of acceptable chars of name. In your case you can try to use #ref.

Categories