I'm new to EF, using 6.0 code-first.
using (EmpolyeeContext emp = new EmpolyeeContext())
{
var callrecordSession = new CallRecordingSession();
string ucid = new Random().Next(0, 5000).ToString();
callrecordSession.UCID = ucid;
callrecordSession.InstrumentationTransactionId = new Random().Next(0, 9000).ToString();
callrecordSession.ClientName = "IVR";
callrecordSession.ClientRequestObject = "{string.empty}";
callrecordSession.CallRecordingStatusName = "Started";
callrecordSession.ModifiedDatetime = DateTime.Now;
emp.CallRecordingSessions.Add(callrecordSession);
var itemToEdit = emp.CallRecordingSessions.Where(c => c.UCID == ucid).FirstOrDefault<CallRecordingSession>();
if (itemToEdit != null)
{
itemToEdit.CallRecordingStatusName = "Inprogress";
itemToEdit.ModifiedDatetime = DateTime.Now;
}
emp.SaveChanges();
}
What is wrong with this code? I'm always getting itemtoEdit as null
Entity Framework always queries the data source. This is by design. If they queried your local cache instead, You could get an Id that has already been inserted by a different user in the database. Also Entity framework has to merge results from your memory and the database.
var itemToEdit = emp.CallRecordingSessions.Where(c => c.UCID == ucid).FirstOrDefault<CallRecordingSession>();
So all you got to do is call the savechanges before you get the data back.
emp.CallRecordingSessions.Add(callrecordSession);
emp.SaveChanges();
var itemToEdit = emp.CallRecordingSessions.Where(c => c.UCID == ucid).FirstOrDefault<CallRecordingSession>();
if (itemToEdit != null)
{
itemToEdit.CallRecordingStatusName = "Inprogress";
itemToEdit.ModifiedDatetime = DateTime.Now;
}
emp.SaveChanges();
.SaveChanges() did the tricks.
Related
string dppath = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "user.db3");
db = new SQLiteConnection(dppath);
string DELETEPASSCODE_DETAIL = "DELETE FROM Table1;";
db.Execute(DELETEPASSCODE_DETAIL);
db.Close();
Hello. When the program executes the above code and reaches the below code, I get this error: cannot create commands from unopened database
try
{
string dpPath = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "user.db3");`
if (dpPath.IndexOf("user.db3") < 0)
{
CreateDB();
CreateTable();
}
else
{
if (db == null)
{
db = new SQLiteConnection(dpPath);
}
var tableExist = db.GetTableInfo("Table1");
……
The error occurs on this db.GetTableInfo("Table1");
I made some mistakes for the first check of the code. Now, I reproduced this issue.
The db can not be null, delete the If statement.
Change:
if (db == null)
{
db = new SQLiteConnection(_databasePath);
}
var tableExist = db.GetTableInfo("Info");
var table_Info = db.Table<Info>().ToList();
To:
db = new SQLiteConnection(_databasePath);
var tableExist = db.GetTableInfo("Info");
var table_Info = db.Table<Info>().ToList();
db.Table<Info>().ToList() could also be used to get the table information.
I'm facing a strange Issue when I'm inserting or updating an item in SharePoint2019 list which contains a user column the save completes with no errors but the user column always have empty value,
below is my code
context.Load(context.Web, web => web.Lists);
await context.ExecuteQueryAsync();
List RiskList = context.Web.Lists.GetByTitle("Risks");
context.Load(RiskList);
context.Load(RiskList, r => r.Fields);
await context.ExecuteQueryAsync();
ListItem listItem = RiskList.GetItemById(projectRisks.Id);
List<ListItemFormUpdateValue> listItemFormUpdateValue = new List<ListItemFormUpdateValue>();
if (projectRisks.AssignedTo.HasValue)
{
listItem["AssignedTo"] = new FieldUserValue() { LookupId = projectRisks.AssignedTo.Value };
}
if (projectRisks.Owner.HasValue)
{
User OwnerUser = context.Web.SiteUsers.GetById(projectRisks.Owner.Value);
context.Load(OwnerUser);
await context.ExecuteQueryAsync();
listItem["Owner"] = new FieldUserValue() { LookupId = OwnerUser.Id };
}
listItemFormUpdateValue.Add(new ListItemFormUpdateValue() { FieldName = "Category", FieldValue = GetSPSelectedChoiceValue(context, RiskList, "Category", projectRisks.CategoryName).Result });
listItemFormUpdateValue.Add(new ListItemFormUpdateValue() { FieldName = "Status", FieldValue = GetSPSelectedChoiceValue(context, RiskList, "Status", projectRisks.StatusName).Result });
listItem["Contingency_x0020_plan"] = projectRisks.ContingencyPlan;
listItem["Cost"] = projectRisks.Cost;
listItem["Cost_x0020_Exposure"] = string.Empty;
listItem["Description"] = projectRisks.Description;
listItem["DueDate"] = projectRisks.DueDate;
listItem["Exposure"] = projectRisks.Exposure;
listItem["Impact"] = projectRisks.Impact;
listItem["Mitigation_x0020_plan"] = projectRisks.MitigationPlan;
listItem["Probability"] = projectRisks.Probability;
listItem["Title"] = projectRisks.Name;
listItem.ValidateUpdateListItem(listItemFormUpdateValue, false, string.Empty);
listItem.Update();
await context.ExecuteQueryAsync();
as you can see in the AssignTo and in Owner Columns no mater how I try to save the users values the list will take the default value which is null.
I have made sure that there is values in the assigned to and Owner properties and I have tried using the ListItemFormUpdateValue but with no luck.
Thanks in advance
i am using sql server which is case sensitive. How can i convert the data so that it may be validated without being case sensitive
CODE:-
using (var kk = new TeamRepository(context))
{
var data = new Team();
var find = kk.GetAll().ToString();
if (find.Any(x => x.TeamName == apview.TeamName))
{
return false;
}
else
{
var _pointrepo = new PointsRepositotry(context);
if (image != null)
{
apview.ImageMimeType = image.ContentType;
apview.TeamLogo = new byte[image.ContentLength];
image.InputStream.Read(apview.TeamLogo, 0, image.ContentLength);
}
data.TeamLogo = apview.TeamLogo;
data.TeamName = apview.TeamName;
data.TeamEmail = apview.TeamEmail;
data.Contact_Number = apview.ContactNumber;
data.TeamNickName = apview.TeamNickName;
data.YearEstablished = apview.YearEstablished;
var points = new Points();
points.TeamName = apview.TeamName;
data.ImageMimeType = apview.ImageMimeType;
return kk.Insert(data);
//_pointrepo.Insert(points);
}
you can use ToLower
find.Any(x => x.TeamName.ToLower() == apview.TeamName.ToLower())
https://msdn.microsoft.com/en-us/library/e78f86at%28v=vs.110%29.aspx
I am trying to implement a let's say "change my account email address" fonctionality.
I want to keep backup of all user emails in (R_EmailAddressHistory table).
Here are some of my project's code.
public bool ChangeEmailAddress(string username, string newEmailAddress, string callbackUrl)
{
DateTime currentUtcTime = DateTime.UtcNow;
R_User currentUser = UserRepo.GetSingle(whereCondition: w=>w.Username == username);
currentUser.UpdateDate = currentUtcTime;
if (currentUser.HasPendingNewEmail)
{
R_EmailAddressHistory currentPendingRequest = EmailHistoRepo.GetSingle(whereCondition: w => w.StatusID == (int)Reno.Common.Enums.RecordStatus.Pending && w.R_User.GId == currentUser.GId);
currentPendingRequest.NewEmail = newEmailAddress;
currentPendingRequest.UpdateDate = currentUtcTime;
EmailHistoRepo.Update(currentPendingRequest);
}
else
{
currentUser.HasPendingNewEmail = true;
R_EmailAddressHistory newEmail = new R_EmailAddressHistory();
newEmail.UserId = currentUser.GId;
newEmail.R_User = currentUser;
newEmail.NewEmail = newEmailAddress;
newEmail.InsertDate = currentUtcTime;
newEmail.StatusID = (int) Reno.Common.Enums.RecordStatus.Pending;
currentUser.R_EmailAddressHistory.Add(newEmail);
}
IdentityResult idtResult = UserRepo.Update(currentUser);
if(idtResult == IdentityResult.Succeeded)
{
//Send notification to current email address for validation before proceeding change email process
bool sendResult = Communication.EmailService.SendChangeEmailValidation(username,currentUser.Email, newEmailAddress, callbackUrl);
return sendResult;
}
else
{
return false;
}
}
The previous method is use to change an email address. Each of my tables (R_User and EmailAddressHistory ) has Repository (UserRepo and EmailHistoRepo). The implement the same IRepositoryBase class, here is the Update methode
public IdentityResult Update(T entity)
{
try
{
if (_currentContext.DbContext.Entry(entity).State == EntityState.Detached)
{
_currentContext.DbContext.Set<T>().Attach(entity);
}
_currentContext.DbContext.Entry(entity).State = EntityState.Modified;
return IdentityResult.Succeeded;
}
catch
{
return IdentityResult.Failed;
}
}
When a user has already a non validate new email address, when he request to change his current email address, I show him the pending new email address and he can change it, in this case I whant to update my historical table instead of creating a new one, cause only one pending new email address is allow. In such a case, my code failed in the line EmailHistoRepo.Update(currentPendingRequest) throwing the error : An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
Can anyone help me?
Thanks
EDIT
I am using MVC(4) with a unitOfWork. My UOW is initialized in a the Controller the first time the DB is queried and the Commit is done in the global.asax file in Appalication_EndRequest (see below).
protected void Application_EndRequest(Object sender, EventArgs e)
{
CommitChanges();
}
private void CommitChanges()
{
Reno.BLL.Services.Singleton.UnitOfWork unitOfWork = Reno.BLL.Services.Singleton.UnitOfWork.GetCurrentInstance(false);
if (unitOfWork != null)
{
unitOfWork.Commit();
unitOfWork.Dispose();
}
}
Your currentUser is modified before updating the emailaddress. Save the changes to currentUser first.
Something like this:
R_User currentUser = UserRepo.GetSingle(whereCondition: w=>w.Username == username);
currentUser.UpdateDate = currentUtcTime;
bool pendingNewEmail = currentUser.HasPendingNewEmail;
UserRepo.Update(currentUser);
if (pendingNewEmail)
{
R_EmailAddressHistory currentPendingRequest = EmailHistoRepo.GetSingle(whereCondition: w => w.StatusID == (int)Reno.Common.Enums.RecordStatus.Pending && w.R_User.GId == currentUser.GId);
currentPendingRequest.NewEmail = newEmailAddress;
currentPendingRequest.UpdateDate = currentUtcTime;
EmailHistoRepo.Update(currentPendingRequest);
}
else
I finally found the answer. The problem was that when I first get the user in line
R_User currentUser = UserRepo.GetSingle(whereCondition: w=>w.Username == username);
The currentUser variable hold a refrence of all of its R_EmailAddressHistory.
And then after, I queried the DB (2nd time) to get the pending email change request (or type R_EmailAddressHistory) to modify its new email and its update date, in line
R_EmailAddressHistory currentPendingRequest = EmailHistoRepo.GetSingle(whereCondition: w => w.StatusID == (int)Reno.Common.Enums.RecordStatus.Pending && w.R_User.GId == currentUser.GId);
currentPendingRequest.NewEmail = newEmailAddress;
currentPendingRequest.UpdateDate = currentUtcTime;
But te last code updates only currentPendingRequest while another reference of the same object which is in currentUser.R_EmailAddressHistory is not update and was already tracked by the context. Therefore, by doing an update on the new instance (EmailHistoRepo.Update(currentPendingRequest)), the code failed: the same object if referenced in 2 places.
So, the solution was (the only thing I modified):
R_User currentUser = UserRepo.GetSingle(whereCondition: w=>w.Username == username);
currentUser.UpdateDate = currentUtcTime;
if (currentUser.HasPendingNewEmail)
{
R_EmailAddressHistory currentPendingRequest = currentUser.R_EmailAddressHistory.Where(h => h.StatusID == (int)Reno.Common.Enums.RecordStatus.Pending).First(); // EmailHistoRepo.GetSingle(whereCondition: w => w.StatusID == (int)Reno.Common.Enums.RecordStatus.Pending && w.R_User.GId == currentUser.GId);
currentPendingRequest.NewEmail = newEmailAddress;
currentPendingRequest.UpdateDate = currentUtcTime;
}
I decided to modify the instance in currentUser variable.
I have an ASP.NET MVC 3 project using .NET framework 4.0 and LINQ to SQL. Because I have serious problems of performance with some queries the first time they are executed I decided to use Entity Framework 5 in order to take advantage of the new LINQ auto compiled feature.
Now I have installed VS 2012, .NET framework 4.5 and Entity Framework 5 and changed my project to point to the .NET framework 4.5 as well as updated my Data Context file to use EF5. The queries now have exactly the same performance, some of them are so slow at the first time execution that even I get a time out exception, the second time everything is fine, I am wondering if the problem is that maybe the migration process was not correct and I am using still the EF4 or it is just a problem of my query construction which can't use the auto compiled feature for an unknown reason.
The EntityFramework dll has the 5.0 version, and the System.Data.Entity dll the version 4, that is right, isn't? Any suggestions?
I include the most problematic query, it retrieves paginated the result for a grid (Telerik MVC grid) which I need to build through 2 queries (originally was a SQL sentence with a sub query):
/// <summary>
/// Get the elements for the AppLog grid.
/// </summary>
public void GetAppLogElements(
int clientID, string language, int functionID, int errorLevel,
int numPage, int pageSize, IList<IFilterDescriptor> filterDescriptors, IList<SortDescriptor> sortDescriptors, IList<GroupDescriptor> groupDescriptors,
ref IQueryable<Model_AppLog> rows, ref int numRows)
{
string orderString = string.Empty;
var items =
from ap in objDataContext.applicationLogs
where
ap.clientID == clientID &&
ap.recordGroup != null
join alf in objDataContext.appLogFunctions on
new { functionID = ap.functionID.Value } equals new { functionID = alf.functionID }
join ale in objDataContext.appLogErrorLevels on
new { errorLevel = ap.errorLevel.Value } equals new { errorLevel = ale.errorLevelID }
join als in objDataContext.appLogSeverities on
new { severity = ap.severity.Value } equals new { severity = als.severityID }
group new { ap, alf, als } by new { ap.functionID, ap.recordGroup, ap.clerkID } into queryGrouped
select new Model_AppLog()
{
sequence = queryGrouped.Max(c => c.ap.sequence),
functionID = queryGrouped.Key.functionID,
recordGroup = queryGrouped.Key.recordGroup,
clerkID = queryGrouped.Key.clerkID,
date = queryGrouped.Min(c => c.ap.date),
errorLevel = (queryGrouped.Max(c => c.ap.errorLevel) == null || !queryGrouped.Max(c => c.ap.errorLevel).HasValue ? 0 : queryGrouped.Max(c => c.ap.errorLevel)),
severity = queryGrouped.Max(c => c.ap.severity)
};
if (errorLevel != -1)
items = items.Where(column => column.errorLevel >= errorLevel);
var _items =
from subSelect in items
join alf in objDataContext.appLogFunctions on
new { functionID = subSelect.functionID.Value } equals new { functionID = alf.functionID }
join alft in objDataContext.appLogFunctionTexts on
new { alf.functionID, language } equals new { alft.functionID, alft.language }
join ale in objDataContext.appLogErrorLevels on
new { errorLevel = subSelect.errorLevel.Value } equals new { errorLevel = ale.errorLevelID }
join alet in objDataContext.appLogErrorLevelTexts on
new { errorLevelID = subSelect.errorLevel.Value, language } equals new { alet.errorLevelID, alet.language }
join als in objDataContext.appLogSeverities on
new { severity = subSelect.severity.Value } equals new { severity = als.severityID }
join alst in objDataContext.appLogSeverityTexts on
new { als.severityID, language } equals new { alst.severityID, alst.language }
select new Model_AppLog()
{
sequence = subSelect.sequence,
functionID = subSelect.functionID,
recordGroup = subSelect.recordGroup,
clerkID = subSelect.clerkID,
date = subSelect.date,
errorLevel = subSelect.errorLevel,
severity = subSelect.severity,
functionDescription = alft.denotation,
errorLevelDescription = alet.denotation,
severityDescription = alst.denotation
};
//Apply filters
if (filterDescriptors != null && filterDescriptors.Any())
{
_items = _items.Where(ExpressionBuilder.Expression<Model_AppLog>(filterDescriptors));
}
if (functionID != -1)
_items = _items.Where(column => column.functionID == functionID);
//Apply sorting
if (sortDescriptors != null)
{
GlobalMethods objGlobalMethods = new GlobalMethods();
orderString = objGlobalMethods.GetOrderString(sortDescriptors);
}
//Apply ordering
if (orderString != string.Empty)
_items = _items.OrderBy(orderString);
else
_items = _items.OrderByDescending(x => x.date);
//Set total number of rows
numRows = _items.AsEnumerable<Model_AppLog>().Count();
//Get paginated results
_items = _items.Skip(pageSize * (numPage - 1)).Take(pageSize);
//Set data result
rows = _items;
}
Here's a paper about EF performance: MSDN
The most important thing you can do to improve start up time is to precompile your views ( there's a section near the end of the MSDN paper )
If you're using database first, there's a T4 template here you can use.
If you're using code first, there's a project here, although I haven't tried it myself.
Note: when you upgrade your project from .NET 4.0 to .NET 4.5, you have to uninstall the EF NuGet package and reinstall it - there are different version of EF 5 for the different runtimes.