I'm trying to get a table (entity) from the entity framework context and all I have is a string parameter input to my service.
In ADO.NET I'd do something like:
var tableName = "tablePrefix" + inputString;
How do I solve this in EF?
Any help will be much appreciated :)
To get a Dbset dynamically without knowing the type upfront you can use the Set method on the DbContext. So you could do.
var type = Type.GetType("MyType");
var set = myContext.Set(type);
Once you have the set you can then query to find an entity by primary key etc.
As Kirill says though, why do you want to do this?
Cheers
Chris
Related
I created my temporal table following instructions on this link "Cutting Edge - Soft Updates with Temporal Tables"
The procedure generally takes two steps:
create the regular table; this is just the kind of work that Code First usually does
alter the table by adding SysStartTime, SysEndTime columns and turning on the SYSTEM_VERSIONING setting
Everything looks good so far.
However, please note that the entity class doesn't have SysStartTime property and SysEndTime property as they are added later. This gives me trouble as I need to get information of SysStartTime from table.
My question is: How can I get it with Entity Framework?
The link also says:
In EF 6, you can only leverage the SqlQuery method of the DbSet class:
using (var db = new EF6Context())
{
var current = db.Bookings.Single(b => b.Id == 1);
var time = DateTime.Now.AddMinutes(-5);
var old = db.Bookings
.SqlQuery("SELECT * FROM dbo.Bookings
FOR SYSTEM_TIME AS OF {0} WHERE Id = 1", time)
.SingleOrDefault();
}
Note that for EF 6, the column names returned in the query need to match the property names on the class. This is because SqlQuery doesn’t use mappings. If column and property names don’t match, then you’d need to alias the columns in the SELECT list, rather than just SELECT *.
I have no clue how to do this or if it solves my problem. Does anyone have any experience on this?
I can think of one solution is to added an extra column AppliedTime on my table by adding AppliedTime to my entity class. It has (almost, but good enough for me) same value as SysStartTime.
Another solution could be use plain SQL to query the table directly.
Thanks.
I have been worked on this one and found a solution. It is actually quite simple. Just use Database.SqlQuery Method
DateTime time = context.Database.SqlQuery<DateTime>("SELECT SysStartTime
FROM dbo.Calibration
WHERE CalibrationID = 1")
.SingleOrDefault();
See Also: Raw SQL Queries
we are developing a framework that through the one url, generate a query based on the mapped entities by entity framework.
We are using the Dynamic Library ( http://lcs3.syr.edu/faculty/fawcett/handouts/CoreTechnologies/CSharp/samples/CSharpSamples/LinqSamples/DynamicQuery/Dynamic%20Expressions.html) and we are struggling to return to the fields of a relationship 1..N.
Example:
TB_PEOPLE > TB_PHONE
Based on this relationship, I need to accomplish the same idea of following linq:
var sql = from p in context.SomeTable
select new {
NAME = p.NAME,
PHONES = p.TB_PHONE.Select(ph => ph.PHONE)
};
Since I'm not working with typing, we chose to use dynamic library because apparently allowed us the flexibility to manipulate strings to return.
Then following the same idea , we set up the following line:
var sql = context.SomeTable.Select("new (TB_PEOPLE.TB_PHONE.PHONE)");
In this case , the returns an error stating that the attribute "PHONE" does not exist "TB_PEOPLE" of course ! So much so that we try to say that this attribute belongs to the table "TB_PHONE" but he does not understand.
So I ask you, how do I return to only certain fields of an entity where the relationship can be N? Also tried to call the method "Select":
var sql = context.SomeTable.Select("new (TB_PEOPLE.TB_PHONE.Select(PHONE))");
...there but I am informed that this method can not be used.
I do not know what else to do, any help will be appreciated!
Thank you.
I am using Dapper to Update and Insert Access DB. Code is working not throwing exception but its not updating the value in DB. Below is my code
sql.Append("UPDATE drugs_repository SET drug_name = #DrugName ");
sql.Append(" WHERE id = #DrugId");
var parameters = new
{
DrugName = objDrug.DrugName,
DrugId = objDrug.DrugId
};
var t = connection.Query<string>(sql.ToString(), parameters);
Can someone please let me know what exactly I am missing in the above code?
When I hardcode the value than its updating in the DB. So probably its related to parameter.
If you are nervous about possible side-effects from removing the .OrderBy() in the Dapper code then a workaround would be to name your parameters in such a way that they will sort in the same order that they appear in the SQL command. For example, I suspect that the unmodified Dapper code would probably work okay if the parameters were named #1DrugName and #2DrugId.
I'm executing this simple query with Entity Framework
db.Database.SqlQuery<string>("SELECT * FROM hospital");
But I got this error:
The data reader has more than one field. Multiple fields are not valid for EDM primitive or enumeration types.
What could be the problem?
It would be useful to see what the hospital table looks like but assuming something simple like hospital consists of HospitalId and HospitalName then you have a couple of choices.
//would work if all you're trying to do is get the Name:
db.Database.SqlQuery<IEnumerable<string>>("SELECT hospitalName FROM hospital");
//where you define MyEntity as the same structure as the table would work
db.Database.SqlQuery<MyEntity>("SELECT * FROM hospital");
// would theoretically work although I haven't tried it. Where the Tuple
// items would have to match the database types in order. I.e. if field 1
// is an int and field 2 is a string then Tuple<int,string>
db.Database.SqlQuery<IEnumerable<Tuple<int, string>>>("SELECT * FROM hospital");
Basically the error is the code doesn't know how to stuff the structure of hospital into a string
You might also get this error if you are trying to execute an INSERT, UPATE or DELETE using SqlQuery instead of using ExecuteSqlCommand
using (var ctx = new SchoolDBEntities())
{
int noOfRowUpdated = ctx.Database.ExecuteSqlCommand("Update student
set studentname ='changed student by command' where studentid=1");
int noOfRowInserted = ctx.Database.ExecuteSqlCommand("insert into student(studentname)
values('New Student')");
int noOfRowDeleted = ctx.Database.ExecuteSqlCommand("delete from student
where studentid=1");
}
For more details visit -
http://www.entityframeworktutorial.net/EntityFramework4.3/raw-sql-query-in-entity-framework.aspx
This solved my issue, some results where not getting the way it was supposed to
string storedProcedure = "Admin_AutoGenerateKeywordsFortblCompany #Company_ID="
+ CompId;
var s = db.ExecuteStoreQuery<List<string>>("exec " + storedProcedure).ToList();
here single or multiple results can be caught
Based on the secound answer that cgotberg gave me, Im going to answer my own question.
The problem with that code was that some table's field was not the same as it is in the database(I was looking for the exception but I could not found it, sorry for that) but it actually exist.
For some reason i had to add all the fields of the tables to the query string. I mean, i had to write "SELECT hospital_phone, holpital_street, etc, etc FROM hospital", if i write "SELECT hospital_name FROM hospital" the exception occurs.
Hope I've it explained well.
I'm having an issue with the Where clause in a search, in my original version EF4 I could add a Where clause with 2 parameters, the where clause (string predicate) and a ObjectParameter list such as
var query = context.entities.Where(WhereClause.ToString(), Params.ToArray());
since my upgrade to EF5 I don't seem to have that option am I missing something?
This was originally used to build dynamic where clause such as "it.entity_id = #entity_id" then holding the variable value in the ObjectParameter.
I'm hoping I don't have to rewrite all the searches that have been built out this way, so any assistance would be greatly appreciated.
Cheers
In order to use ESQL with DbContext, you will have to "drop down" to ObjectContext.
var objectContext = ((IObjectContextAdapter)context).ObjectContext;
var query = objectContext.CreateQuery<MyEntity>(
WhereClause.ToString(),
Params.ToArray());