Entity Framework get specific column from a string - c#

I have a Web API project that uses Entity Framework. I have an action api/account that given an ID returns that account.
There is an additional parameter that can be provided which is what fields to be returned e.g. api/account?field=name
I'm trying to work out the best way of translating from this string input to Entity Framework. I know I can use .Select() to only get certain columns but that takes in a Func and the only way I can think of getting from the string to a Func is by using Reflection. This seems like it will be a peformance hit if I have to do Reflection for every property passed in, is there a better way of doing this?
Thanks

You can use this library System.Linq.Dynamic from Nuget, and this query
var selectStatement = string.Format("new ({0},{1})", field1, field2);
var result = db.Users.Select(selectStatement).ToListAsync().Result;

Related

Entity Framework C# queries from string parameters

I'm creating a web app based on a database. The datas in the database need to be displayed, edited and deleted by the web app user.
Right now I need to remove elements in my sqlite database table after the user inputs the name of the database table and the id (which is also the primary key) of the element. How can I do it?
I always used Entity Framework before and also in the Web App so I was looking for a solution with it, but if there's a simpler way to do it, I'll stick with it.
Thank you
I think the answer here is similar but I need help to adapt it to what I need now.
Entity Framework C# queries from strings
this is the UI
and here is the endpoint in the backend
//DELETE method
[HttpDelete("DeleteElementInTable")]
public IActionResult DeleteElementInTable(string tableName, string elementKey) //url query parameters
{
var db = new MyContext();
//code to remove the item ... something like:
DbManager.RemoveElement(tableName, elementKey); //DbManager is the static class dealing with the db context
return //csv of the deleted element;
}
I'm still a young developer but here I can see there are some lacks of knowledge. First of all, which technology are you using to build your web-app? From what you posted my guess is you are trying to use MVC. As #Panagiotis Kanavos said above you need an entity to interact with the database if you want to use Entity Framework, through which you don't need to pass table name in your GET function. Last but not less important you can't execute the delete operation in a GET function.

Use JSON_ARRAYAGG with Entity Framework Core

I am trying to use JSON_ARRAYAGG(JSON_OBJECT(...)) in Entity Framework Core but I don't know much how to trick Entity Framework Core to use this function with a custom IQueryable<T>.
Does anybody have any simple example how this can be achieved ?
I can not build a raw query because the IQueryable is built dynamically based on params, but my idea was to first build the IQueryable<T> and then somehow combine that with the given functions. Lets take a simple example of what I want to achieve:
var people = await db.People.Select(x => new Person { Name = x.Name, Surname = x.Surname }).ToListAsync();
This will translate to:
select name, surname from people;
I want to have:
select JSON_ARRAYAGG(JSON_OBJECT("name", name, "surname", surname) from people;
One solution is to get the query from the IQueryable and do a nasty replace on the final string, but this does not seem a very good solution.
Is there any way I can modify the list of params on runtime without using replace function ?

LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method,

I am using Entity Framework, and I have a line of code that convert string field (id)to int and compare with a number
students = students.Where(s => (Int32.Parse( s.id)>5555));
Whenever I try to run it I receive rhis error. "LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method, and this method cannot be translated into a store expression."
I have tried seveal different things and nothing is working, so any help would be great.
Firstly I would highly recommend against converting the column into an int, you lose the indexing on the column. You rather convert the int into a string. However here is how to fix your code.
Firstly sign the Contributor License Agreement.
Then you fork the Entity Framework git repo.
Write a new MethodCallTranslator.CallTranslator which will take Convert.ToInt32(string) and replace it with (int) string.
Register the new MethodCallTranslator.CallTranslator within MethodCallTranslator.
Write unit tests for your test case.
Check in
Create Pull Request
Wait
Download new version of Entity Framework from nuget

asp.net entity framework keys in response

I am trying to write my first RESTful API in C# using ASP.NET Web API and Entity Framework.
My issue is that the list that returns from my EF query is polluted with entity key information that is useless (I found out that because my columns are nullable if thinks they all must be keys).
Here is a part of the XML response I receive from my API call
<syemploy z:Id="i1"><EntityKey z:Id="i2">
<d2p1:EntityContainerName>AbraHRMS_LiveEntities</d2p1:EntityContainerName>
<d2p1:EntityKeyValues>
<d2p1:EntityKeyMember>
<d2p1:Key>id_col</d2p1:Key>
<d2p1:Value i:type="d5p1:int">15</d2p1:Value>
</d2p1:EntityKeyMember>
<d2p1:EntityKeyMember>
<d2p1:Key>e_address1</d2p1:Key>
<d2p1:Value i:type="d5p1:string">153 Townsend Street, Suite 9057</d2p1:Value>
</d2p1:EntityKeyMember>
...
How can I remove the entity key values from the response?
My c# code looks like this
AbraHRMS_LiveEntities _db = new AbraHRMS_LiveEntities();
# GET api/employee
public List<MvcApplication1.DAL.syemploy> Get()
{
return _db.syemploys.ToList();
}
Again, this is my first API in C#, so if anything is funky looking please feel free to point it out.
By default you'll have all public properties of your entities in XML. To avoid having them in response, try to create "new" class which doesn't contain undesirable fields and then convert your result to the list of "new" type objects. You can use .Select() or .Cast() on _db.syemployes for that. Keep in mind that syemploy class should be convertible to "new" class in case you want to call Cast<> method. You can read here about type conversion in C#. If you use .Select() then construct objects of new type inside of select's lambda expression.

Converting IQueryable<T> object to another object?

I have no idea what the keywords are so here is an example of what I want:
return from i in userRepo.GetUsers()
select new SimpleUser{
i.UserId,
i.Name
};
userRepo.GetUsers() returns type IQueryable<User>. I'd like to convert this to IQueryable<SimpleUser> to I can restrict access to certain properties of the User domain.
How do I do this without hard coding the translation like this? What about tools like automapper or ValueInjecter, how can they do this?
Also, what is this technique called?
You must hardcode the translation or you must first convert it to IEnumerable. IQueryable represents expression tree translated to some execution in used provider - in your case I believe it will be Entity framework. You can't use any automatic mapping in such query because it will be translated to SQL which will not understand your .net methods or AutoMapper. Projections to custom types are part of the query and must be hardcoded. You can create custom extension method to IQueryable and reuse it where you need:
public static IQueryable<SimpleUser> ProjectToSimpleUser(this IQueryable<User> query)
{
return query.Select(u => new SimpleUser
{
// Here map your fields
});
}
Now you can use:
return repo.GetUsers().ProjectToSimpleUser();
In case of Entity framework SimpleUser mustn't be an mapped entity.
Provided that SimpleUser is assigneable to User (User is an interface of baseclass of SimpleUser), you can
var users = simpleUsers.Cast<User>();
optionally with
var users = simpleUsers.Cast<User>().AsQueryable();
And if you're not sure whether all items are actually Users, then you can use OfType<User> instead of Cast<User>
AutoMapper is the tool you want; it works via reflection and unless you tell it to do otherwise, it will map properties with the same name directly.
Auto-mapping is the technique.
This question is 9 years old so idk if it existed then but for anyone searching now, using .FirstOrDefault() works if you pick a single user.

Categories

Resources