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

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;
...

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" };

Entity framework condidional query building

I have problem with creating complex query with entity framework. I would like to fetch additional data into my linq entity based on parameters given during construction of such query. Here is example with where:
if (featureEnabled)
{
query = query.Where(n => *condition*);
}
I have complex object created like that:
n => new Entity{
Property = n.Something
\* ... *\
PropertyN = n.SomethingN,
}
and I want to load additional data into entity if feature is enabled (just like in where example):
public DoSomething(bool featureEnabled, feature2Enabled, etc.)
{
return n => new Entity{
Property = n.Something,
\* ... *\
PropertyN = n.SomethingN,
Feature = (featureEnabled) ? *fetch some data from navigation property* : 0,
Feature2 = (feature2Enabled) etc.
}
}
In above example parameters (featureNEnabled) will be translated into sql parameters. How to perform such operation at query construction time?
did you mean inside the initializer you want use the if condition?
if its so i will have its not possible. To use the if condition you have to put it outside the initializer
var a = new MyClass{
prop1 = n.prop1,
prop2 = n.prop2,
prop3 = n.prop3,
};
a.propN = boolCondition ? n.PropN : 0;
I finally found answer to my question on this blog
With this code you may call expression.Merge(expression2) and initialization lists of two objects will be merged into one query.

Create reference to a class from a string variable [duplicate]

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

Dynamic table name in linq [duplicate]

This question already has answers here:
Querying data using Entity Framework from dynamically created table
(2 answers)
Dynamically set the table name in LINQ query
(3 answers)
Closed 8 years ago.
I'm trying to execute some LINQ commands using a dynamic table name. For example, instead of:
var o = (from x in context.users select x);
I want to use something like:
var o = (from x in getTableObjectByName("users", context) select x);
More or less. Here's the code I have so far, which both compiles and runs:
using (MySiteEntities ipe2 = new MySiteEntities()) {
var propinfo1 = Type.GetType("MySiteNamespace.MySiteEntities").GetProperty("users");
var propval1 = propinfo1.GetValue(ipe2, null);
}
That runs, but always returns zero records. The users table most definitely contains records, and in any case when I call it directly using the first method above I get all of the records as expected. How can I modify my code to actually pull down records, rather than just an empty collection?
Edit: I've also tried this:
using (MySiteEntities ipe = new MySiteEntities())
{
var prop = Type.GetType("MySiteNamespace.MySiteEntities").GetProperty("users");
Type dbsetType = typeof(DbSet<>);
dbsetType = dbsetType.MakeGenericType(Type.GetType("MySiteNamespace.user"));
Type t = dbsetType.GetType();
var val = prop.GetValue(ipe, null);
}
In this case, the code not only runs, but actually returns the results as expected. However, val is an Object. I need to cast it to the type DbSet<user>, which would be easy enough, except that the parameter user is only known at runtime....the cast needs to be dynamic as well. I've tried using Convert.ChangeType(val, t);, but that throws an
InvalidCastException (Object must implement IConvertible).
How can I convert the val variable to an actually usable object?
No idea if this is relevant, but this is on EntityFramework 4.
In your DbContext class, add a method say called Set that returns:
public DbSet Set(string name)
{
// you may need to fill in the namespace of your context
return base.Set(Type.GetType(name));
}
Which you can query like this:
using (var db = new YourDataContext())
{
// Since your DbSet isn't generic, you can can't use this:
// db.Set("Namespace.EntityName").AsQueryable().Where(a=> a.HasSomeValue...
// Your queries should also be string based.
// Use the System.Linq.Dynamic nuget package/namespace
var results = db.Set("Namespace.EntityName")
.AsQueryable()
.Where("SomeProperty > #1 and SomeThing < #2", aValue, anotherValue);
// you can now iterate over the results collection of objects
}
More information on System.Linq.Dynamic can be found here

When to use var and when to use Strongly types? [duplicate]

This question already has answers here:
Use of var keyword in C#
(86 answers)
Closed 9 years ago.
I have class like below.
public class Dropdown
{
[Required(ErrorMessage = "Please select state")]
public string StateId { get; set; }
public List<SelectListItem> States
{
get
{
return new List<SelectListItem>()
{
new SelectListItem
{
Text = "State1",
Value = "S1",
Selected = false
},
new SelectListItem
{
Selected = false,
Value = "S2",
Text = "State2"
}
};
}
}
}
In Action Method, I have below two options while instantiating this class.
Approach 1
var d = new Models.Dropdown();
Approach 2
Models.Dropdown d = new Models.Dropdown();
Both are show same number of Methods/Properties/Data Members etc. I also heard that it is recommended to use Approach 1
Question
Is my assumption correct to use Approach 1 ?
The var keyword is compiler feature which allows implicit type declarations - I would opt to use var purely because it's shorter.
People will probably say you lose readability using var, however, what makes
MyClass myobj = new MyClass()
any more readable than
var myobj = new MyClass()
The only scenario where I do think it does make sense to use an explicit type is when declaring an interfaced type i.e.
IMyInterface myobj = new MyClass()
Or casting
MyBaseClass myObj = new MyClass()
Then again, you could argue those cases as well because the same code would be functionality equivalent
var myObj = (IMyInterface)new MyClass()
var myObj = (MyBaseClass)new MyClass()
In general, I very rarely see the need to explicitly define the type as it's inferred by the instantiated type.
Both are equivalent, in fact if you write #1 the compiler will resolve it to #2. What matters then is thee readability.
There is a long debate on why var should be avoided just because it has a negative impact on readability. My opinion is that it should be avoided when possible, however in extreme cases writing an explicit type for an expression could be just too cumbersome (just write a complicated linq expression with groupping or double groupping and try to write down its type).
There is no difference except for readability.
I'd pick Approach 1 because I consider it more readable.
for var the type is inferred. So there is no difference for both approaches from the type point of view.
As var is more readable, Stylecop suggests to use var whenever possible
Please have a look at this question to get the full information.

Categories