Not able to access list of record in EF - entity-framework

Here is the problem I am trying to access some records from the data base based on one field . The field I am using is audit_id having type GUID .
but the line does not returning any data
var audits = ctx.Audits.Where(x => lstAudits.Contains(x.audit_id)).ToList();
Here is a my full code to update mass records in the database using EF
//will select auditId from the List
var lstAudits = _ViewModel.WorkingListAudits.Where(x => x.WorkingList).Select(x=>x.AuditId).ToList();
using (var ctx = new AuditEntities())
{
var audits = ctx.Audits.Where(x => lstAudits.Contains(x.audit_id)).ToList();
audits.ForEach(x => x.working_list = false);
ctx.SaveChanges();
}
In case of single record it return data from database
var lstAudits = _ViewModel.WorkingListAudits.Where(x => x.WorkingList).Select(x => x.AuditId).ToList();
Guid tempAuditId = lstAudits[0];
// lstAudits.ForEach(x => x.ToString().ToUpper());
using (var ctx = new AuditEntities())
{
var audits = (from au in ctx.Audits
where au.audit_id == tempAuditId
select au).ToList();
//foreach(Audit audit in audits){
//}
audits[0].working_list = false;
ctx.SaveChanges();
}
Finally I got the answer here is the updated code which is working fine .I just took some intermediate result in a temporary variable and it started working as expected
//will select auditId from the List
var lstAudits = _ViewModel.WorkingListAudits.Where(x => x.WorkingList).Select(x => x.AuditId).ToList();
using (var ctx = new AuditEntities())
{
var tempAudits = ctx.Audits.ToList();
var audits = tempAudits.Where(x => lstAudits.Contains(x.audit_id)).ToList();
audits.ForEach(x => x.working_list = false);
ctx.SaveChanges();
}

Related

UpdateRange method of Entity Framework Core does not work

The UpdateRange method of Entity Framework Core is used here to update multiple records but it is not working.
My code is:
var dept1 = new Department()
{
Id = 8,
Name = "New Designing"
};
var dept2 = new Department()
{
Id = 9,
Name = "New Research"
};
var dept3 = new Department()
{
Id = 102,
Name = "New HR"
};
List<Department> modifiedDept = new List<Department>() { dept1, dept2, dept3 };
using (var context = new CompanyContext())
{
context.UpdateRange(modifiedDept);
await context.SaveChangesAsync();
}
And the error I get is:
Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: 'Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.'
What should be done in this case?
You are supposed to get data from database and modify data. Not creating new class.
using (var context = new JobContext())
{
var depts = context.Department.Where(x => x.Id > 1).AsQueryable();
depts.Where(x => x.Id == 2).FirstOrDefault().Name = "New Designing";
depts.Where(x => x.Id == 3).FirstOrDefault().Name = "New Research";
depts.Where(x => x.Id == 4).FirstOrDefault().Name = "New HR";
context.UpdateRange(depts);
context.SaveChanges();
}
Before
After

Remove and Insert in table , Removing previous data using Entity frame work in asp.net core

When trying to insert "FromCompany" data to "ToCompany" after saveChanges(); it deleted "FromCompany" data.
I am trying to delete old data , and copy the data from another company to mycompany, but it deleting the data from that comapny after saving it in my company.
This is the example code:
foreach (var data in ctx.AllData.Where(a => a.CompanyId == toCompanyId).Select(a => a).ToList())
{
ctx.AllData.Remove(data);
}
ctx.SaveChanges();
var alldata = ctx.AllData.Where(a => a.CompanyId == fromCompanyId ).Select(a => a).ToList();
foreach (var data in alldata)
{
var model = new AllData();
data.CompanyId = toCompanyId;
model.CompanyId = data.CompanyId;
model.CategoryId = data.CategoryId;
model.OtherFields = data.OtherFields;
ctx.AllData.Add(model);
}
ctx.SaveChanges();
In the second foreach you are changing the data.CompanyId. Then calling ctx.SaveChanges you are changing all companies with fromCompanyId. Try to remove that line, like this:
foreach (var data in ctx.AllData.Where(a => a.CompanyId == toCompanyId).Select(a => a).ToList())
{
ctx.AllData.Remove(data);
}
ctx.SaveChanges();
var alldata = ctx.AllData.Where(a => a.CompanyId == fromCompanyId ).Select(a => a).ToList();
foreach (var data in alldata)
{
var model = new AllData();
model.CompanyId = toCompanyId;
model.CategoryId = data.CategoryId;
model.OtherFields = data.OtherFields;
ctx.AllData.Add(model);
}
ctx.SaveChanges();
While you are calling ctx.SaveChanges you are saving all changes were performed in all context's data.

Where to place AsNoTracking on a Entity Framework query?

I have the following Entity Framework Core 2.2 query:
IQueryable<Job> jobs = _context.Jobs.AsNoTracking();
jobs = jobs.Where(x => x.Active);
jobs.Skip(offset).Take(limit);
var result = jobs
.Select(x => new {
Id = x.Id,
Country = new {
Code = x.Country.Code,
Name = x.Country.Name
},
JobTypes = _context.JobTypes.Select(x => x.Name),
Created = x.Created,
Skills = x.JobSkills.Select(y => new {
Id = y.Skill.Id,
Name = y.Skill.Name
})
});
return await result.ToListAsync();
I am using AsNoTracking() to make the query faster. The question is:
Is there a specific place where to place AsNoTracking()?
Should I place it before ToListAsync instead of in the beginning?

Prevent sort result of union in entity framework

In SQL server union, result is sorted based on primary key column. I want to prevent this behavior in entity framework.
In this post, #praveen has explained how to do this in pure sql. But I want to do this in entity framework.
My code:
public virtual ActionResult Search(string keyword)
{
var products = _db.Products
.Where(x => x.IsActive)
.AsQueryable();
var productExactlyTitle = products.Where(x => x.Title == keyword);
var productStartTitle = products.Where(x => x.Title.StartsWith(keyword));
var productContainsTitle = products.Where(x => x.Title.Contains(keyword)
|| x.Title.Contains(keyword)
|| x.SubTitle.Contains(keyword)
|| x.OtherName.Contains(keyword));
var productList = productExactlyTitle.Union(productStartTitle)
.Union(productContainsTitle)
.Take(10)
.AsEnumerable()
.Select(x => new ProductItemViewModel()
{
Id = x.Id,
Title = x.Title,
Price = x.Price.ToPrice(),
Image = x.Images.FirstOrDefault(y => y.IsCoverPhoto)?.ImageUrl
});
// some code ...
}
I want to show records with below order:
First: records of productExactlyTitle
Second: records of productStartTitle
Third: records of productContainsTitle
But result is sorted with Id column! and I don't want this.
Is there a way for do this?
In SQL all queries without an order by explicitly set is considered unordered. (and EF queries a translated into SQL). So if you want a specific order after your union just specify it.
var result = q1.Union(q2).OrderBy(x => x.?);
For your specific case:
var p1 = productExactlyTitle.Select(x => new { Item = x, Order = 1 });
var p2 = productStartTitle.Select(x => new { Item = x, Order = 2 });
var p3 = productContainsTitle.Select(x => new { Item = x, Order = 3 });
var productList = p1.Union(p2)
.Union(p3)
.OrderBy(x => x.Order)
.Select(x => x.Item)
.Take(10);

how to update a record in database using LINQ?

I want to do the following in LINQ:
update [dbo].[AdminLogin] set [ADMIN_PASSWORD] = 'abc' where [ADMIN_ID] = 1
where i get the admin password from a model and the admin id is stored in a variable:
var userid = (from m in db.RequestPasswordReset
where m.Id == Unid
select m.UserId).FirstOrDefault();
How to do it?
To update an entity you must have to specify the Modified state.
using (var db= new DbContext())
{
var entity= db.AdminLogin.Where(x => x.ADMIN_ID == userid ).SingleOrDefault();
entity.ADMIN_PASSWORD = 'abc';
db.Entry(entity).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
}
see details here
use this code:
using (var context = new YourContext())
{
var res = context.AdminLogin.Where(x => x.ADMIN_ID == userid ).SingleOrDefault();
res.ADMIN_PASSWORD = 'abc';
context.SaveChanges();
}
You can try this:
var user = db.AdminLogin.FirstOrDefault(x => x.ADMIN_ID == id);
user.ADMIN_PASSWORD = 'abc';
db.SaveChanges();
userid.ADMIN_PASSWORD= 'abc';
db.SaveChanges(); //better then db.SubmitChanges() in some case
If you using linQ.dbml file then you have to write like this:
using (var db= new DbContext())
{
var entity= db.AdminLogin.Where(x => x.ADMIN_ID == userid ).FirstOrDefault();
entity.ADMIN_PASSWORD = 'abc';
db.SubmitChanges();
}