I am getting the role being created but the description does not get updated.
I have tried in two ways:
First:
Roles.CreateRole(model.RoleName);
using (tgpwebgedEntities context = new tgpwebgedEntities())
{
var query = from r in context.aspnet_Roles where r.RoleName == r.RoleName select r;
var obj = query.First();
obj.Description = model.Description;
context.SaveChanges();
}
Second:
using(tgpwebgedEntities context = new tgpwebgedEntities()) {
var obj = context.aspnet_Roles.Single(r => r.RoleName == roleModel.RoleName);
obj.Description = roleModel.Description;
context.SaveChanges();
}
The curious thing is that this second way is the way I am using when the user is editing an aready created role using another action and works fine.
This first is used in a method that created the role and update its description since there is no support for description in .NET.
The problem is with your query statement,
var query = from r in context.aspnet_Roles where r.RoleName == r.RoleName select r;
"r.RoleName == r.RoleName" which will always be true and returns all entries. The query should be something similar to what you have in the second query
r => r.RoleName == roleModel.RoleName
Related
I want to update my db like
var context = new asb_cardEntities3();
var query = db.WFileMaster.Where(q => q.ID ==
data.ID).FirstOrDefault();
query.SUBE = item.SUBE.ToString();
query.HES_NO = item.HES_NO.ToString();
query.DVZ_KOD = item.DVZ_KOD.ToString();
query.TUTAR = item.TUTAR.ToString();
//context.Entry(query).State = SUBE.Modified;
context.SaveChanges();
this, I did not get any error (all data come) I am new in this framework, I think problem is in context. But I did not find any solution.
Please change db to context while retrieving the record in the second line.
var context = new asb_cardEntities3();
var query = context.WFileMaster.Where(q => q.ID == data.ID).FirstOrDefault();
query.SUBE = item.SUBE.ToString();
query.HES_NO = item.HES_NO.ToString();
query.DVZ_KOD = item.DVZ_KOD.ToString();
query.TUTAR = item.TUTAR.ToString();
context.SaveChanges();
Before saving changes update the table
something like that
.Update(x => x.Id== ID, object); and then
save changes.
i'm new in entity framework.Below is my code,
So in my code i have created object of my db context and then i have a query 'queryForAuthentication' and in that i have used two tables 'conDb.SystemMasters' and joined with conDb.SystemAdminMasters , so will hit twice or how does it manage . i want to know when does entity framework will hit in to database ?
QuizzrEntities conDb = new QuizzrEntities();
List<OnLoginData> lstOnLogoonData = new List<OnLoginData>();
string userpassWordHash = string.Empty;
var queryForAuthentication =from systemObj in conDb.SystemMasters
where systemObj.StaffPin == dminLoginInput.StaffPin
join admin in conDb.SystemAdminMasters on systemObj.SystemId equals admin.SystemID
select new
{
admin.PasswordSalt,
admin.PasswordHash,
systemObj.StaffPin,
admin.UserName,
admin.SystemID
};
if (queryForAuthentication.Count() > 0)
{
CheckStaffPin = true;
var GetUserUsingUsernamePasword = queryForAuthentication.Where(u => u.UserName.ToLower() == AdminLoginInput.UserName.ToLower());
if (GetUserUsingUsernamePasword.ToList().Count == 1)
{
checkuserName = true;
string DBPasswordSalt = queryForAuthentication.ToList()[0].PasswordSalt,
DBPasswordHash = queryForAuthentication.ToList()[0].PasswordHash,
StaffPin = queryForAuthentication.ToList()[0].StaffPin;
userpassWordHash = Common.GetPasswordHash(AdminLoginInput.Password, DBPasswordSalt);
if ((DBPasswordHash == userpassWordHash) && (AdminLoginInput.StaffPin.ToLower() == StaffPin.ToLower()))
{
checkPassword = true;
CheckStaffPin = true;
}
else if (DBPasswordHash == userpassWordHash)
{
checkPassword = true;
}
else if (AdminLoginInput.StaffPin.ToLower() == StaffPin.ToLower())
{
CheckStaffPin = true;
}
}
}
So in my code i have created object of my db context and then i have a query 'queryForAuthentication' and in that i have used two tables 'conDb.SystemMasters' and joined with conDb.SystemAdminMasters , so will hit twice or how does it manage .
i want to know when does entity framework will hit in to database ?
It's hits the database whenever you fire a query. And query will be fired whenever you perform ToList, First, FirstOrDefault etc. operation. Till then it only builds the query.
try Code
QuizzrEntities conDb = new QuizzrEntities();
List<OnLoginData> lstOnLogoonData = new List<OnLoginData>();
string userpassWordHash = string.Empty;
var queryForAuthentication =(from systemObj in conDb.SystemMasters
where systemObj.StaffPin == dminLoginInput.StaffPin
join admin in conDb.SystemAdminMasters on systemObj.SystemId equals admin.SystemID
select new
{
PasswordSalt= admin.PasswordSalt,
PasswordHash= admin.PasswordHash,
StaffPin= systemObj.StaffPin,
UserName= admin.UserName,
SystemID = admin.SystemID
}).FirstOrDefault();
If(queryForAuthentication !=null)
{
-----------------
-----------------
*****Your Code*******
}
In entity framework also work with sql query based. If you are disconnected using .ToList() then only the record taken from local otherwise it's works as DBQuery. if you check the result view in debug view it's Execute the Query and Return the data.
If you are processing the data is discontinued from the base it's executed finally where you want the result.
You processing data locally then you can disconnect the connection between linq and sql using call .ToList(). it's Processing only one time the Object weight is high more than query.
var queryForAuthentication =from systemObj in conDb.SystemMasters
where systemObj.StaffPin == dminLoginInput.StaffPin
join admin in conDb.SystemAdminMasters on systemObj.SystemId equals admin.SystemID
select new
{
admin.PasswordSalt,
admin.PasswordHash,
systemObj.StaffPin,
admin.UserName,
admin.SystemID
}.ToList() ; // It will fetch the data
//Check from inmemory collection
if (queryForAuthentication.Count > 0)
//As you already have the data in memory this filter applied against inmemory collection not against database.
var GetUserUsingUsernamePasword = queryForAuthentication
.Where(u =>u.UserName.ToLower() == AdminLoginInput.UserName.ToLower());
"Property or indexer cannot be assigned to -- it is read only"
i see a lot of similar question though none actually seem to help me.
i am updating some rows in my db.
first i call my data:
var projects = (from p in _ProjectRep.GetAll()
join cl in _ClientRepo.GetAll() on p.ClientID equals cl.ClientID
where p.IsOpen == true && p.Tasks.Any(t => t.TimeEntries.Any(te => te.DateEntity >= dateLimit)) == false && p.Tasks.Any(te => te.TimeEntries.Any())
select new {
TickProjectID = p.TickProjectID,
ClientName = cl.ClientName,
ProjectName = p.ProjectName,
IsOpen = p.IsOpen,
DateClosed = p.DateClosed
}).ToList();
Then i try to loop through that data, and update specific fields in those records.
foreach (var item in projects)
{// Update projects to closed.
item.IsOpen = false;
item.DateClosed = DateTime.Now;
}
and lastly save the data..
// updates changes to OUR db.
var affectedCount = _UnitOfWork.SaveChanges();
But i keep getting that error, and i do not know what to do about it.
What i can read it is something about get/set, but i have none of those,
and i cannot see why those should be nessesary ?
Hoping someone can give a clear solution, that might help me.
Edit
private readonly ProjectRepository _ProjectRep;
_ProjectRep = new ProjectRepository(unitOfWork);
var projects = (from p in _ProjectRep.GetAll()
join cl in _ClientRepo.GetAll() on p.ClientID equals cl.ClientID
where p.IsOpen == true && p.Tasks.Any(t => t.TimeEntries.Any(te => te.DateEntity >= dateLimit)) == false && p.Tasks.Any(te => te.TimeEntries.Any())
select p).ToList();
Try this. Problem in your code is, that you are working with anonymous type (created using new {...}). This type doesn't know anything like change tracking, its properties are read only, so this type can not be used to save changes to database.
it seems my sql call was anonymous, and therefore it did not know what it was.
i changed my sql call select
var projects = (from p in _ProjectRep.GetAll()
join cl in _ClientRepo.GetAll() on p.ClientID equals cl.ClientID
where p.IsOpen == true && p.Tasks.Any(t => t.TimeEntries.Any(te => te.DateEntity >= dateLimit)) == false && p.Tasks.Any(te => te.TimeEntries.Any())
select new {
Project = p,
ClientName = cl.ClientName
}).ToList();
and then i just have to call "Project.{something}" when i wanted to select data.
like this:
foreach (var item in projects)
{// Update projects to closed.
item.Project.IsOpen = false;
item.Project.DateClosed = DateTime.Now;
}
that made the whole thing work.
Well, im doing a linq query to get a list of results with the same column, and then i need to replace that column value with a new one.
First Code:
var db = GetContext();
var result = from f in GetContext().ProjectStateHistories
where f.ProjectId.Equals(oldProjectId)
select f;
foreach (var item in result)
{
var projectStateHistoryUpdate = db.ProjectStateHistories.Find(item.Id);
projectStateHistoryUpdate.ProjectId = newProjectId;
db.Entry(projectStateHistoryUpdate).State = EntityState.Modified;
}
db.SaveChanges();
I searched for some answers, and i found that i can use Select, and make a new object (Linq replace null/empty value with another value)
Second Code:
var result = (from f in GetContext().ProjectStateHistories
where f.ProjectId.Equals(oldProjectId)
select f).Select(d=> new { Id = d.Id, EventName = d.EventName, LogUser = d.LogUser, ProjectId = newProjectId, TimeStamp = d.TimeStamp });
And even, Third Code:
var db = GetContext();
var result = (from f in db.ProjectStateHistories
where f.ProjectId.Equals(oldProjectId)
select f).Select(d=> new { ProjectId = newProjectId});
But only the First Code works.
I wanted to ask what i am doing wrong, since i think it is better to change the value with a query, instead of using a foreach.
See code below:
var db = GetContext();
(from f in db.ProjectStateHistories
where f.ProjectId.Equals(oldProjectId)
select f)
.ToList()
.ForEach(i => i.ProjectId = newProjectId);
db.SaveChanges();
Alternatively:
var db = GetContext();
db.ProjectStateHistories
.Where(f => f.ProjectId.Equals(oldProjectId))
.ToList()
.ForEach(f => f.ProjectId = newProjectId);
db.SaveChanges();
The shortest way I know of to replace your code is this:
var db = getcontext();
db.ProjectStateHistories
.Where(f => f.ProjectId.Equals(oldProjectId))
.ToList()
.ForEach(f => f.ProjectId = newProjectId);
db.SaveChanges();
Other answers can be found here
I've just had a thought that could help you, I am just free coding here!
If you just put the for each as part of the select, and then save your changes will that work?
foreach (var source in db.ProjectStateHistories.Where(x => x.ProjectId == oldProjectId))
{
source.ProjectId= newProjectId;
db.Entry(source).State = EntityState.Modified;
}
db.SaveChanges();
I think this is a more efficient way of doing it.
Also the .Select() method is only really useful if you need to Project to a view Model, it won't change the variables in the database, just show them in the newly declared object.
Thanks,
Phill
I have build a query to return data from two tables in which they are joined by inner join. Although, as the query seems fine, i am getting error message when i try to access the selected field names from the query. How do i use .SingleOrDefault() function in this query. Can anybody help me how should i proceed.
private void FindByPincode(int iPincode)
{
using (ABCEntities ctx = new ABCEntities())
{
var query = from c in ctx.Cities
join s in ctx.States
on c.StateId equals s.StateId
where c.Pincode == iPincode
select new {
s.StateName,
c.CityName,
c.Area};
// var query = ctx.Cities.AsNoTracking().SingleOrDefault(_city => _city.Pincode == iPincode);
if (query != null)
{
cboState.SelectedItem.Text =query.State; //Getting error "Could not found"
cboCity.SelectedItem.Text = query.CityName; //Getting error "Could not found"
txtArea.Text = query.Area; //Getting error "Could not found"
}
}
}
Thanks in advance.
Try this:
using (ABCEntities ctx = new ABCEntities())
{
var query = (from c in ctx.Cities
join s in ctx.States
on c.StateId equals s.StateId
where c.Pincode == iPincode
select new {
s.StateName,
c.CityName,
c.Area}).FirstOrDefault();
if (query != null)
{
cboState.SelectedItem.Text =query.State;
cboCity.SelectedItem.Text = query.CityName;
txtArea.Text = query.Area;
}
}
can it be that you are selecting a field named StateName, and then acessing State.
cboState.SelectedItem.Text =query.State;
cboState.SelectedItem.Text =query.StateName;
Please provide more details on the error and the class structure of your code
Here's how a similar situation worked for me:
using (ABCEntities ctx = new ABCEntities())
{
var query = (from c in ctx.Cities
join s in ctx.States
on c.StateId equals s.StateId
where c.Pincode == iPincode
select new {
s.StateName,
c.CityName,
c.Area}).Single();
if (query.Any())
{
cboState.SelectedItem.Text =query.State;
cboCity.SelectedItem.Text = query.CityName;
txtArea.Text = query.Area;
}
}
Notice that i used query.Any() up there, that is because query != null will always return true. However any() checks if a query has returned 1 or more records, if yes Any() returns true and if a query returns no records then Any() returns false.