EntityFrameworkCore FromSql method call throws System.NotSupportedException - asp.net-mvc

So am using AspNetCore 1.0 with EFCore 1.0, both latest releases as far as I am aware.
Executing a query to delete an object using the FromSql method on a DbSet throws an exception. Both the code and exception are below.
public void DeleteColumn(int p_ColumnID)
{
int temp = p_ColumnID;
string query = "DELETE FROM Columns WHERE ID = {0}";
var columnsList = m_context.Columns.FromSql(query, p_ColumnID).ToList();
foreach (Columns c in columnsList)
{
m_context.Columns.Remove(c);
}
m_context.SaveChanges();
}
After executing the FromSql call, I get the following exception
An exception of type 'System.NotSupportedException' occurred in Remotion.Linq.dll but was not handled in user code
Additional information: Could not parse expression 'value(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[ASPNET5_Scrum_Tool.Models.Columns]).FromSql("DELETE FROM Columns WHERE ID = {0}", __p_0)': This overload of the method 'Microsoft.EntityFrameworkCore.RelationalQueryableExtensions.FromSql' is currently not supported.
I have no clue how to fix this error and from Googling I have come across no similar problems.
I am also wondering, if the query/code was successful it would return an 'IQueryable object. Would that solely contain the results of the query, in this case the specific Column object to delete?

FromSql is intended to allow you to compose a custom SQL SELECT statement that will return entities. Using it with a DELETE statement is not appropriate here, since your goal is to load the records you want to delete and then delete them using the default Entity Framework mechanism. A Delete statement generally does not return the records deleted (though there are ways to accomplish that). Even if they did, the records will already be deleted and so you won't want to iterate over them and do a Remove on them.
The most straightforward way to do what you want might be to use the RemoveRange method in combination with a Where query.
public void DeleteColumn(int p_ColumnID)
{
m_context.Columns.RemoveRange(m_context.Columns.Where(x => x.ID == p_ColumnID))
m_context.SaveChanges();
}
Alternately, if you want to load your entities and iterate manually through them to
public void DeleteColumn(int p_ColumnID)
{
columnList = m_context.Columns.Where(x => x.ID == p_ColumnID);
foreach (Columns c in columnsList)
{
m_context.Columns.Remove(c);
}
m_context.SaveChanges();
}
If you really want to issue the Delete statement manually, as suggested by Mike Brind, use an ExecuteSqlCommand method similar to:
public void DeleteColumn(int p_ColumnID)
{
string sqlStatement = "DELETE FROM Columns WHERE ID = {0}";
m_context.Database.ExecuteSqlCommand(sqlStatement, p_ColumnID);
}

I had the same exception in a case where I did not use delete statement. Turns out I was using the In-Memory Database. Since it is not a real database you can't use FromSQL.

Related

How to delete tenant completely?

I'm developing a multitenant application and would like to have to option to remove a tenant. This however seems to be less trivial than one would assume.
My goal is to delete all references to the tenant everywhere in the database. I understand that Tenant is Soft-Delete, but I since I don't want my database to fill up with old meaningless data I've tried disabling the soft-delete filter.
Here is some code that I've tried:
using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.SoftDelete))
{
await TenantRepository.DeleteAsync(x => x.Id == tenantId);
}
This did not work. The tenant is marked as "IsDeleted" but not removed.
Then I figured that maybe it has something to do with UnitOfWork so I made sure no UnitOfWork was active and then manually controlled it:
using (var unitOfWork = _unitOfWorkManager.Begin())
{
// the codeblock above went here
unitOfWork.Complete();
}
This did not work, same result. And this is just the AbpTenant table. I'm also trying to delete from all other tables. For example AbpSettings and AbpLanguages. It's very unclear to me how to do that at all - the "managers" doesn't contain any Delete functions.
I tried creating IRepository for these entities but it does not work. The error reads
The type Abo.Configuration.Setting cannot be used as a type parameter TEntity in the generic type or method IRepository. There is no implicit reference conversion from Abp.Configuration.Setting to Abo.Domain.Entities.IEntity.
That leaves me with the option to use the DataContext directly:
using (EntityFramework.MyDbContext db = new EntityFramework.MyDbContext())
{
List<PermissionSetting> perms = await db.Permissions.Where(x => x.TenantId == tenantId).ToListAsync();
for (int i=0; i<perms.Count(); i++)
{
db.Permissions.Remove(perms[i]);
}
// I also tried deleting them in bulk at first
// ((DbSet<PermissionSetting>)db.Permissions).RemoveRange(db.Permissions.Where(x => x.TenantId == tenantId));
await db.SaveChangesAsync();
}
I tried that with and without UnitOfWork.
But it simply does not get deleted from the database. I'm getting no errors or Exceptions.
Why does it not get deleted? How can I delete it? Surely it must be possible?
since I don't want my database to fill up with old meaningless data I've tried disabling the soft-delete filter.
From the question on Disable SoftDelete for AbpUserRole:
protected override void CancelDeletionForSoftDelete(EntityEntry entry)
{
if (IsSoftDeleteFilterEnabled)
{
base.CancelDeletionForSoftDelete(entry);
}
}
The type Abo.Configuration.Setting cannot be used as a type parameter TEntity in the generic type or method IRepository. There is no implicit reference conversion from Abp.Configuration.Setting to Abo.Domain.Entities.IEntity.
Inject IRepository<Setting, long> instead of IRepository<Setting>.
That leaves me with the option to use the DataContext directly
...
But it simply does not get deleted from the database. I'm getting no errors or Exceptions.
From the documentation on Data Filters:
using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.MayHaveTenant))
{
using (var db = new ...)
{
// ...
}
}
That said, there is no way to easily delete related tenant data completely. Consider writing SQL.

Will SaveChanges inside Entity Framework wraps all changes in a database transaction

I have the following method inside my asp.net mvc web application, and i am using Ado.net entity framework to map my current database tables:-
public void changeDeviceSwitch(int fromID , int toID)
{
var currentdevices = tms.TMSSwitchPorts.Where(a => a.SwitchID == fromID);
foreach (var d in currentdevices)
{
tms.TMSSwitchPorts.Remove(d);
}
foreach (var d in currentdevices)
{
TMSSwitchPort tsp = new TMSSwitchPort()
{ SwitchID = toID,
TechnologyID = d.TechnologyID,
PortNumber = d.PortNumber };
tms.TMSSwitchPorts.Add(d);
}
tms.SaveChanges();
}
My above method will generate multiple delete and add operations inside the database. so let say it will result in 5 delete operations and 5 insert operations, in this case will calling the SaveChangies() in my case, wraps the 10 operations in one database transaction ?, so either all changes happen or none of them ?
Thanks
That is correct, SaveChanges acts like transaction meaning nothing is happening until you call it explicitly (nothing is sent to DB), and once you call it, everything is sent at once, and if one query/command fails, no changes will be persisted.
If you however want to send queries to SQL in batches, but still treat them as single transaction, you might look into what Entity Framework 6 has to offer (MSDN Article). Basically, you can wrap several SaveChanges in one big transaction, and if any of the queries/commands sent to SQL fails, in any of the batches, it will allow you to do a rollback of everything.

Entity Framework Optimistic Concurrency with Update stored procedure (Julie Lerman example)

I'm having some difficulties understanding the Concurrency problem using Update store procedures. I'm following Julie Lerman's Programming Entity Framework and she gives the following code in an example:
using (var context = new BAEntities())
{
var payment = context.Payments.First();
if (payment.PaymentDate != null)
{
payment.PaymentDate = payment.PaymentDate.Value.AddDays(1);
}
var origRowVersion = payment.RowVersion;
try
{ //BREAKPOINT #1
context.SaveChanges();
var newRowVersion = payment.RowVersion;
if (newRowVersion == origRowVersion)
{
Console.WriteLine("RowVersion not updated");
}
else
{
Console.WriteLine("RowVersion updated");
}
}
catch (OptimisticConcurrencyException)
{
Console.WriteLine("Concurrency Exception was thrown");
}
}
The Update SP looks like:
UPDATE payments
SET paymentdate=#date,reservationID=#reservationID,amount=#amount, modifieddate=#modifiedDate
WHERE
paymentid=#paymentid AND ROWVERSION=#rowversion
IF ##ROWCOUNT>0
SELECT RowVersion AS newTimeStamp FROM payments WHERE paymentid=#paymentid
and the "Use original value" checkbox is ticked in the mapping, which looks like this:
https://dl.dropboxusercontent.com/u/135754/updatemapping.png
Now, when I try to:
run the code as it is, then the newRowVersion inspected in the debugger is same as origRowversion, but the app enters 'else' clause (why is it the same in the first place, I have just changed it? is it debugger issue?)
run the code, but in the BREAKPOINT #1 I update the payment object in Management Studio, the SaveChanges throws OptimisticConcurrencyException. I assume this is expected result.
Each time when I look in the SQL Profiler, the original version of timestamp is sent to the server.
Then, when I untick the "Use original value" in the SP mappings for the timestamp value, everything works the same way as described above... I don't get the idea of it. Am I testing it wrong? When is the app supposed to enter the 'if' clause?
Thanks in advance, cheers!
EDIT:
I added newTimeStamp as the return value for the Update SP mapping. Now I can see that the updated value of RowVersion is correctly taken from the DB. But I still cannot see the difference between having "Use original value" checked and unchecked...
I think I get it now.
When I try to manually change the rowversion (to a random byte[]) before calling savechanges then:
Use Original Value unchecked: the 'random byte[]' is sent to the DB and used in the update stored procedure (in WHERE clause), causing OptimisticConcurrencyException
Use Original Value checked: the value that rowversion had when it was originally downloaded from DB is sent and used in the update stored procedure (in WHERE clause)
I guess this is what Use Original Value is for... It just seems a little weird to me, who would change it manually in the same dbcontext?

The specified LINQ expression contains references to queries that are associated with different contexts

am getting this error on this code (this is an MVC project into which I am trying to integrate Entity Framework):
List<string> consultantSchoolList = new List<string>();
// districts managed by consultant
IQueryable<string> consultClients = rc.consultantDistrictsRepository.districtsForConsultant(userID);
// schools managed by consultant
if (consultClients != null)
{
consultantSchoolList = (from c in rc.clientsRepository.Clients
where (consultClients.Contains(c.cdsCode.Substring(0, 7)))
select c.cdsCode).ToList();
}
on the "consultantSchoolList = " line.
This is an MVC project and I am using a context object that is stored in the HttpContext.Current object. Each repository has a private variable that stores the context object, but each one should point to the same object in the HttpContext.Current Items collection. Would this be considered two different contexts even though they point to the same thing?
Stepping through the code in the debugger shows that the context objects for the two repositories, consultantDistrictsRepository and clientsRepository, do point to the same object in the HttpContext.Current object.
UPDATE Here's how I define the context objects in each repository:
private SchedulerContext context;
public EFConsultantDistricts()
{
context = ContextHelper.GetContext();
}
and GetContext is as follows:
public static SchedulerContext GetContext()
{
if (!HttpContext.Current.Items.Contains("_db_context"))
{
HttpContext.Current.Items.Add("_db_context", new SchedulerContext());
}
return (SchedulerContext)HttpContext.Current.Items["_db_context"];
}
I found the problem -- I was caching the frequently-requested clients list in a Session variable in the Clients repository:
if (HttpContext.Current.Session["clientList"] == null)
{
HttpContext.Current.Session["clientList"] = from c in context.Clients
where (c.Year == fiscalYear)
select c;
}
return (IQueryable<Client>)HttpContext.Current.Session["clientList"];
Since the Session object persists over requests, I guess it was using a previous context object. I thought the client list would be separated from the context object, but I guess not if I'm using IQueryable.
I hate to hit the database every time for this, but I guess I have no choice ... at least for the moment until I get everything straightened out.

Executing Method Against DataContext Returning Inserted ID

Is there any way to use DataContext to execute some explicit SQL and return the auto-increment primary key value of the inserted row without using ExecuteMethodCall? All I want to do is insert some data into a table and get back the newly created primary key but without using LINQ (I use explicit SQL in my queries, just using LINQ to model the data).
Cheers
EDIT: Basically, I want to do this:
public int CreateSomething(Something somethingToCreate)
{
string query = "MyFunkyQuery";
this.ExecuteCommand(query);
// return back the ID of the inserted value here!
}
SOLUTION
This one took a while. You have to pass a reference for the OUTPUT parameter in your sproc in your parameter list of the calling function like so:
[Parameter(Name = "InsertedContractID", DbType = "Int")] ref System.Nullable<int> insertedContractID
Then you have to do
insertedContractID = ((System.Nullable<int>)(result.GetParameterValue(16)));
once you've called it. Then you can use this outside of it:
public int? CreateContract(Contract contractToCreate)
{
System.Nullable<int> insertedContractID = null; ref insertedContractID);
return insertedContractID;
}
Take heavy note of GetParameterValue(16). It's indexed to whichever parameter it is in your parameter list (this isn't the full code, by the way).
You can use something like this:
int newID = myDataContext.ExecuteQuery<int>(
"INSERT INTO MyTable (Col1, Col2) VALUES ({0}, {1});
SELECT Convert(Int, ##IDENTITY)",
val1, val2).First();
The key is in converting ##IDENTITY in type int, like Ben sugested.
If you insist on using raw sql queries, then why not just use sprocs for your inserts? You could get the identity returned through an output parameters.
I'm not the greatest at SQL, but I broke out LinqPad and came up with this. It's a big hack in my opinion, but it works ... kinda.
DataContext.ExecuteQuery<T>() returns an IEnumerable<T> where T is a mapped linq entity. The extra select I added will only populate the YourPrimaryKey property.
public int CreateSomething(Something somethingToCreate)
{
// sub out your versions of YourLinqEntity & YourPrimaryKey
string query = "MyFunkyQuery" + "select Convert(Int, SCOPE_IDENTITY()) as [YourPrimaryKey]";
var result = this.ExecuteQuery<YourLinqEntity>(query);
return result.First().YourPrimaryKey;
}
You'll need to modify your insert statement to include a SELECT ##Identity (SQL Server) or similar at the end.

Resources