c# - IDENT_CURRENT in Linq-to-Entities - c#

I am using Linq-to-Entities in my Windows Application and want to execute this SQL statement:
SELECT IDENT_CURRENT ('ProductInfo') AS Current_Identity
I have read another post that is using Database.SqlQuery like this:
int varMaxAdvertiseId = Convert.ToInt32(hmd.Database.SqlQuery<decimal>("Select IDENT_CURRENT ('HMDAdvertiseManage')", new object[0]).FirstOrDefault());
but this is not working with me (intelisense is not showing it) Can someone help me, please ?

var id = hmd.ExecuteStoreQuery<decimal>(#"SELECT IDENT_CURRENT ({0}) AS Current_Identity;",
"HMDAdvertiseManage").First();

If you are using .net 4.0 to 4.8 then you should be careful that your model usually inherit from DbContext then when you want to use ExecuteStoreQuery
then you should get ObjectContext from your model
var context = new YourDbContext();
var adapter = (IObjectContextAdapter)context;
var objectContext = adapter.ObjectContext;
var id = objectContext.ExecuteStoreQuery<decimal>(#"SELECT IDENT_CURRENT ({0}) AS Current_Identity;", "HMDAdvertiseManage").First();
every things is Ok now

Related

SQLite query not executing properly in a WPF project

I'm working on a WPF application and using SQLite database. I can do every CRUD operation with Entity Framework, but in some specific cases I have to use raw SQL queries, and sometimes it's not returning what I need.
Here is a sample code:
using (var db = new DbContext(AppIO.DatabaseFilePath)) {
var key = 12;
string sql = $"SELECT COUNT(*) FROM SomeTable WHERE SomeField={key}";
var result = db.Database.ExecuteSqlCommand(sql);
}
I simplified the example. Here the result, what I got is -1. I copied the sql string value (after it's built) and executed in SQLiteStuido on the same database and it returned the correct value.
The DatabaseFilePath is correct. The connection is set correctly. I'm checking the same databases (in code and in SQLiteStudio). Any other idea?
Try this:
var result = db.Database.SqlQuery<int>(sql).First();
You have to call SqlQuery method and not ExecuteSqlCommand method. Since SqlQuery returns an IEnumerable you have to call Single. This is a the way to retreive scalar values from a query.
using (var db = new DbContext(AppIO.DatabaseFilePath)) {
var key = 12;
string sql = $"SELECT COUNT(*) FROM SomeTable WHERE SomeField={key}";
var result = db.Database.SqlQuery<int>(sql).Single();
}

Get output 'inserted' on update with Entity Framework

SQL Server provides output for inserted and updated record with the 'inserted' keyword.
I have a table representing a processing queue. I use the following query to lock a record and get the ID of the locked record:
UPDATE TOP (1) GlobalTrans
SET LockDateTime = GETUTCDATE()
OUTPUT inserted.ID
WHERE LockDateTime IS NULL
This will output a column named ID with all the updated record IDs (a single ID in my case). How can I translate this into EF in C# to execute the update and get the ID back?
Entity Framework has no way of doing that.
You could do it the ORM way, by selecting all the records, setting their LockDateTime and writing them back. That probably is not safe for what you want to do because by default it's not one single transaction.
You can span your own transactions and use RepeatableRead as isolation level. That should work. Depending on what your database does in the background, it might be overkill though.
You could write the SQL by hand. That defeats the purpose of entity framework, but it should be just as safe as it was before as far as the locking mechanism is concerned.
You could also put it into a stored procedure and call that. It's a little bit better than the above version because at least somebody will compile it and check that the table and column names are correct.
Simple Example #1 to get a data table:
I did this directly against the connection:
Changed the command.ExecuteNonQuery() to command.ExecuteReader()
var connection = DbContext().Database.Connection as SqlConnection;
using (var command = connection.CreateCommand())
{
command.CommandText = sql;
command.CommandTimeout = 120;
command.Parameters.Add(param);
using (var reader = command.ExecuteReader())
{
var resultTable = new DataTable();
resultTable.Load(reader);
return resultTable;
}
}
FYI, If you don't have an OUTPUT clause in your SQL, it will return an empty data table.
Example #2 to return entities:
This is a bit more complicated but does work.
using a SQL statement with a OUTPUT inserted.*
var className = typeof(T).Name;
var container = ObjContext().MetadataWorkspace.GetEntityContainer(UnitOfWork.ObjContext().DefaultContainerName, DataSpace.CSpace);
var setName = (from meta in container.BaseEntitySets where meta.ElementType.Name == className select meta.Name).First();
var results = ObjContext().ExecuteStoreQuery<T>(sql, setName, trackingEnabled ? MergeOption.AppendOnly : MergeOption.NoTracking).ToList();
T being the entity being worked on

Get Data from DB With EF

I've recently started working with EF6 So my knowledge on it isn't very great. I am currently working on test web project which I have created using VS Express 2013. EF has created the required tables. Now I've added my own table which has basic information such as:
FirstName
Surname
DOB
What I'm trying to gather is would I write a SQL query in my function to get the data from the database so something like
using (SqlConnection connection = new SqlConnection(myConnectionString))
{
using (SqlCommand cmd = new SqlCommand("select * from my table", connection))
{
connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
//Read Data
}
}
}
Or is there a separate way to write it in EF? Because I couldn't find how and where the SQL syntax queries are used in EF or maybe I'm just missing something? Thanks in advance for your help & support
Entity Framework (EF) is an object-relational mapper that enables .NET
developers to work with relational data using domain-specific objects.
It eliminates the need for most of the data-access code that
developers usually need to write.
You need to review more there http://msdn.microsoft.com/en-gb/data/ef.aspx and at least read some intros to EF or some video tutorials.
var context = new EntitiesContext();//DbContext Object
var list = ent.Customers; // will return all customers.
The code you have posted is using ADO.Net. You can perform raw sql in entity framework like this
Entities ent = new Entities();//DbContext Object
var list = ent.tablename.SqlQuery("select * from my table");
And using Entity framework to get data from db
Entities ent = new Entities();//DbContext Object
var data = ent.tableName;
The point of EF is that you don't have to write SQL queries. You have an object model you use to access the database:
using (var context = new YourEntities())
{
var records = context.Table; // .Where(t => t.Name == "foo")
foreach (var record in records)
{
// ...
}
}
Please check out the Quickstart example from MSDN
http://msdn.microsoft.com/en-us/library/vstudio/bb399182%28v=vs.100%29.aspx

How to get Schema name from Entity Framework 4.0 objects?

I'm creating some manual SQL updates using C#, Entity Framework 4 and DB2, in the way of this naive example...
var UpdateCommand = "UPDATE MY_SCHEMA." + this.Entities.PRODUCT.EntitySet.Name +
" SET STOCK=0";
var AffectedRows = this.Entities.ExeceuteStoreCommand(UpdateCommand);
I want to specify the schema as with the entity name (which later, if implememented in a reusable library method, could be passed as parameter). So, I tried...
var Container = this.Entities.MetadataWorkspace.GetEntityContainer(this.Entities.DefaultContainerName, System.Data.Metadata.Edm.DataSpace.CSpace);
var Set = Container.GetEntitySetByName(this.Entities.PRODUCT.EntitySet.Name, true);
var SchemaName = Set.MetadataProperties["Schema"].Value;
The problem is that the SchemaName returned is always null!
I've seen solutions based on parsing SQL generated by Entity Framework, but that could be fooled (text can containg anything), or SQL-Server specific. The idea is to be as DB agnostic as EF is.
Question is... how to get an entity schema name from EF objects, not parsing generated SQL and being db-agnostic?
you can get it from SSpace.
In ef5 following works. Probably will work in ef4 also
// for code-first
var Container = this.Entities.MetadataWorkspace.GetEntityContainer("CodeFirstDatabase", DataSpace.SSpace);
// db-first
var Container = this.Entities.MetadataWorkspace.GetEntityContainer("DbFirstModelStoreContainer", DataSpace.SSpace);
var schemaName = Container.GetEntitySetByName(this.Entities.PRODUCT.EntitySet.Name, true).Schema
// or
var set = Container.GetEntitySetByName(this.Entities.PRODUCT.EntitySet.Name, true);
var schemaName = Set.MetadataProperties["Schema"].Value;

last_insert_id ? C#, SQL Server and NHibernate

I need to know how can I know what is the last inserted id in a SQL Server database for a given table?
I'm using int identity not guid and if it's matters NHibernate as my ORM.
Thanks
You could try something like this:
var sql = "SELECT IDENT_CURRENT('TableName')";
var query = session.CreateSQLQuery(sql);
var result = query.UniqueResult();
This will return the last identity value generated for a given table.
Depending on how your ID's are generated, you should be able to return it straight from the ISession.Save():
int insertedID = (int)session.Save(entity);

Categories

Resources