c# - 模型未使用新值更新
问题描述
在应用程序运行时更改值后,我遇到用户模型未使用正确的 ParentAccount ID 更新的问题。
例如
我将运行应用程序并更改联系人父帐户。然后创建一个订单并使用下面的“创建”方法将父帐户分配给该订单。
现在我觉得它应该运行更新当前用户模型的“GetUser”方法,然后获取当前用户并将其分配给销售订单。
相反,它会跳过它并首先运行它下面的代码,并且永远不会使用正确的父帐户 ID 更新它。
有人对为什么会发生这种情况有任何建议吗?
谢谢!
public void Create(CrmContextCore _crmContext, Guid productId, ClaimsPrincipal User)
{
// User Model
UserEntityModel currentuser;
DAL_UserEntity UserData = new DAL_UserEntity();
var EmailAddress = User.Claims.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.Email)?.Value;
var salesorder = new Entity("salesorder");
{
// Go get the current user data from crm system
currentuser = UserData.GetUser(_crmContext, EmailAddress);
// ISSUE! If i change this value while the application is running and rerun the method it shows the old value of currentuser not the new one??
salesorder["customerid"] = new EntityReference("account", currentuser.ParentAccount.Id);
salesorder["contactid"] = new EntityReference("contact", currentuser.ContactId);
salesorder["emailaddress"] = currentuser.Email;
salesorder["name"] = "PO123";
}
_crmContext.ServiceContext.AddObject(salesorder);
_crmContext.ServiceContext.SaveChanges();
}
这是用户模型
public class UserEntityModel
{
public Guid ContactId {get; set;}
public EntityReference ParentAccount { get; set; }
public Guid Account {get; set;}
public string FirstName {get; set;}
public string LastName {get; set;}
public string Email {get; set;}
}
这里是创建用户模型的地方
public class DAL_UserEntity
{
public UserEntityModel GetUser(CrmContextCore _crmContext, string email)
{
Console.WriteLine("GetUser Method is Running!!");
var user = (from u in _crmContext.ServiceContext.CreateQuery("contact")
where u.GetAttributeValue<string>("emailaddress1") == email
select u).Single();
UserEntityModel ctx = new UserEntityModel();
ctx.FirstName = user.GetAttributeValue<string>("firstname");
ctx.LastName = user.GetAttributeValue<string>("lastname");
ctx.Email = user.GetAttributeValue<string>("emailaddress1");
ctx.ContactId = user.GetAttributeValue<Guid>("contactid");
ctx.ParentAccount = user.GetAttributeValue<EntityReference>("parentcustomerid");
return ctx;
}
}
解决方案
您正在创建一个新实体,并从您从数据库中检索到的实体分配值。如果要更新 DB 实体,则需要更新 DB 实体上的字段,或者可以将新实体附加到数据上下文。请参阅这篇文章为什么使用 Attach 来更新 Entity Framework 6?
推荐阅读
- node.js - 节点 - 意外标识符
- java - List 项的垃圾收集
- arduino - 用于餐厅停车的 Arduino 红外传感器
- sql - 如何检查 UNIQUEIDENTIFIER 值并用选择字符串值替换(如果存在)
- excel - 将日期选择器添加到 Excel 2013 的 VBA 用户窗体
- angular - Angular 指令初始化良好实践
- android-studio - 卸载 Android SDK 工具卡住了
- javascript - 为什么我可以用 Date 对象做数学运算?
- java - thread print name with runnable parameter
- docker - 使用自动端口映射时,Docker 应用程序不适用于主机 IP