Asp.net mvc 使用实体框架在ASP.NET Core中添加和更新
我正在将JSON数据添加并更新到SQL表中 下面是用于添加和更新一组新记录的代码Asp.net mvc 使用实体框架在ASP.NET Core中添加和更新,asp.net-mvc,entity-framework,asp.net-core,entity-framework-core,Asp.net Mvc,Entity Framework,Asp.net Core,Entity Framework Core,我正在将JSON数据添加并更新到SQL表中 下面是用于添加和更新一组新记录的代码 List ListKp=new List(); 使用(var事务=_context.Database.BeginTransaction()) { 尝试 { int numP=0; var catalogProducts=_context.catalogProducts.ToList(); foreach(ListKp中的var kp) { 如果(!catalogProducts.Any(x=>x.Name==
List ListKp=new List();
使用(var事务=_context.Database.BeginTransaction())
{
尝试
{
int numP=0;
var catalogProducts=_context.catalogProducts.ToList();
foreach(ListKp中的var kp)
{
如果(!catalogProducts.Any(x=>x.Name==kp.Name))
{
_context.CatalogProducts.Add(kp);
}
其他的
{
//使用AutoMapper自动进行映射
var config=new-MapperConfiguration(cfg=>cfg.CreateMap().ForMember(c=>c.Id,opt=>opt.Ignore());
var oldone=catalogProducts.FirstOrDefault(c=>c.Name==kp.Name);
var mapper=config.CreateMapper();
oldone=mapper.Map(kp,oldone);
_context.CatalogProducts.Update(oldone);
}
}
numP=_context.SaveChanges();
Commit();
返回Json(“无冲突”。+numP+“已保存产品详细信息”);
}
捕获(例外情况除外)
{
transaction.Rollback();
返回Json(“发生错误”。+ex.Message);
抛出新异常();
}
}
示例JSON数据
{
“标题”:“棕色鸡蛋”,
“类型”:“乳制品”,
“描述”:“篮子里的生有机棕色鸡蛋”,
“文件名”:“0.jpg”,
“高度”:600,
“宽度”:400,
“价格”:28.1,
“评级”:4
},
{
“标题”:“甜鲜草莓”,
“类型”:“水果”,
“描述”:“木桌上的甜鲜草莓”,
“文件名”:“1.jpg”,
“高度”:450,
“宽度”:299,
“价格”:29.45,
“评级”:4
},
首先,我将把上面JSON中的[type]键对象值添加到products表[NAME]字段中。它将添加一组新记录
当我尝试用[title]键对象值更新products表[NAME]字段时,它将再次添加一组新记录
需要更新products table[NAME]字段,而无需再次添加
我不知道如何用模型列表值检查表中已经存在的记录。已经在这上面花了很多时间。我是EF Core的新手,任何人都可以帮助我
完整代码
[HttpPost]
public IActionResult InsertProductDetails()
{
using WebClient wc = new WebClient();
string contentString = wc.DownloadString(baseurl);
List<Dictionary<string, string>> ListJsonProductContent = new List<Dictionary<string, string>>();
var token = JToken.Parse(contentString);
if (token.Type == JTokenType.Array) // "["
{
ListJsonProductContent = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(contentString);
}
else if (token.Type == JTokenType.Object) // "{"
{
var ObjectResponse = JsonConvert.DeserializeObject<Dictionary<string, object>>(contentString);
foreach (var x in ObjectResponse)
{
string key = x.Key.ToString();
string val = x.Value.ToString();
foreach (var dicItemML in JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(val))
{
ListJsonProductContent.Add(dicItemML);
}
}
}
List <K360MappingMaster> ListMappedDataDb = new List<K360MappingMaster>();
var VLinqQuery = from KMM in _context.K360MappingMasters
where KMM.ThirdPartyBaseUrlName != null && KMM.ThirdPartyBaseUrlName == baseurl
select KMM;
ListMappedDataDb = VLinqQuery.ToList();
foreach (var dicItemML in ListJsonProductContent)
{
Dictionary<string, string> updItem = new Dictionary<string, string>();
foreach (var itemMl in dicItemML)
{
if (ListMappedDataDb.Select(s => s.ApiCatalog).ToList().Contains(itemMl.Key))
{
if (updItem.ContainsKey(ListMappedDataDb.Where(s => s.ApiCatalog == itemMl.Key).Select(s => s.K360Catalog).FirstOrDefault()))
{
if (ListMappedDataDb.Where(s => s.ApiCatalog == itemMl.Key).Select(s => s.K360Catalog).FirstOrDefault() == "Specification")
{
updItem[ListMappedDataDb.Where(s => s.ApiCatalog == itemMl.Key).Select(s => s.K360Catalog).FirstOrDefault()] += "<p>" + itemMl.Key + " :" + itemMl.Value + "<p>";
}
else
{
updItem[ListMappedDataDb.Where(s => s.ApiCatalog == itemMl.Key).Select(s => s.K360Catalog).FirstOrDefault()] += " " + itemMl.Value;
}
}
else
{
if (ListMappedDataDb.Where(s => s.ApiCatalog == itemMl.Key).Select(s => s.K360Catalog).FirstOrDefault() == "Specification")
{
updItem.Add(ListMappedDataDb.Where(s => s.ApiCatalog == itemMl.Key).Select(s => s.K360Catalog).FirstOrDefault(), "<p>" + itemMl.Key + " :" + itemMl.Value + "<p>");
}
else
{
updItem.Add(ListMappedDataDb.Where(s => s.ApiCatalog == itemMl.Key).Select(s => s.K360Catalog).FirstOrDefault(), itemMl.Value);
}
}
}
dicItemML.Remove(itemMl.Key);
}
foreach (var itemM2 in updItem)
{
dicItemML.Add(itemM2.Key, itemM2.Value);
}
}
List<CatalogProduct> ListKp = new List<CatalogProduct>();
foreach (var dicItem in ListJsonProductContent)
{
CatalogProduct Ctgkp = new CatalogProduct
{
Name = dicItem.ContainsKey("Name") ? dicItem["Name"] : "No Product",
Slug = dicItem.ContainsKey("Name") ? string.Concat(dicItem["Name"].Where(c => !char.IsWhiteSpace(c))).ToLower() : "No Slug",
Price = dicItem.ContainsKey("Price") ? decimal.Parse(dicItem["Price"], CultureInfo.InvariantCulture) : default,
ShortDescription = dicItem.ContainsKey("ShortDescription") ? dicItem["ShortDescription"] : null,
Description = dicItem.ContainsKey("Description") ? dicItem["Description"] : null,
Specification = dicItem.ContainsKey("Specification") ? dicItem["Specification"] : null,
RatingAverage = dicItem.ContainsKey("RatingAverage") ? double.Parse(dicItem["RatingAverage"], CultureInfo.InvariantCulture) : null};
ListKp.Add(Ctgkp);
}
using (var transaction = _context.Database.BeginTransaction())
{
try
{
int numP = 0;
var catalogProducts = _context.CatalogProducts.ToList();
foreach (var kp in ListKp)
{
if (!catalogProducts.Any(x => x.Name == kp.Name))
{
_context.CatalogProducts.Add(kp);
}
else
{
//Use AutoMapper automatically do the mapping
var config = new MapperConfiguration(cfg => cfg.CreateMap<CatalogProduct, CatalogProduct>().ForMember(c => c.Id, opt => opt.Ignore()));
var oldone = catalogProducts.FirstOrDefault(c => c.Name == kp.Name);
var mapper = config.CreateMapper();
oldone = mapper.Map<CatalogProduct, CatalogProduct>(kp, oldone);
_context.CatalogProducts.Update(oldone);
}
}
numP = _context.SaveChanges();
(from q in _context.K360MappingMasters
where q.ThirdPartyBaseUrlName == baseurl
select q).ToList().ForEach(x => x.InsertStatusFlag = true);
_context.SaveChanges();
transaction.Commit();
return Json("No conflicts. " + numP + " product details saved.");
}
catch (Exception ex)
{
transaction.Rollback();
return Json("Error occurred." + ex.Message);
throw new Exception();
}
}
[HttpPost]
公共IActionResult InsertProductDetails()
{
使用WebClient wc=新的WebClient();
string contentString=wc.DownloadString(baseurl);
List ListJsonProductContent=新列表();
var token=JToken.Parse(contentString);
if(token.Type==JTokenType.Array)/“[”
{
ListJsonProductContent=JsonConvert.DeserializeObject(contentString);
}
如果(token.Type==JTokenType.Object)/“{”
{
var ObjectResponse=JsonConvert.DeserializeObject(contentString);
foreach(ObjectResponse中的var x)
{
字符串key=x.key.ToString();
字符串val=x.Value.ToString();
foreach(JsonConvert.DeserializeObject(val)中的var dicItemML)
{
添加(dicItemML);
}
}
}
List ListMappedDataDb=新列表();
var VLinqQuery=来自_context.K360MappingMasters中的KMM
其中KMM.ThirdPartyBaseUrlName!=null&&KMM.ThirdPartyBaseUrlName==baseurl
选择KMM;
ListMappedDataDb=VLinqQuery.ToList();
foreach(ListJsonProductContent中的var dicItemML)
{
Dictionary Updatem=新字典();
foreach(dicItemML中的var itemMl)
{
if(listmapeddatadb.Select(s=>s.ApiCatalog.ToList().Contains(itemMl.Key))
{
if(updItem.ContainsKey(ListMappedDataDb.Where(s=>s.ApiCatalog==itemMl.Key)。选择(s=>s.K360Catalog.FirstOrDefault())
{
if(listmapeddatadb.Where(s=>s.ApiCatalog==itemMl.Key)。选择(s=>s.K360Catalog)。FirstOrDefault()==“规范”)
{
UPDATEM[ListMappedDataDb.Where(s=>s.ApiCatalog==itemMl.Key)。选择(s=>s.K360Catalog)。FirstOrDefault()]+=“”+itemMl.Key+”:“+itemMl.Value+””;
}
其他的
{
UPDATEM[ListMappedDataDb.Where(s=>s.ApiCatalog==itemMl.Key)。选择(s=>s.K360Catalog)。FirstOrDefault()]+=“”+itemMl.Value;
}
}
其他的
{
if(listmapeddatadb.Where(s=>s.ApiCatalog==itemMl.Key)。选择(s=>s.K360Catalog)。FirstOrDefault()==“规范”)
{
添加(ListMappedDataDb.Where(s=>s.ApiCatalog==itemMl.Key)。选择(s=>s.K360Catalog.FirstOrDefault(),“”+itemMl.Key+”:“+itemMl.Value+””;
}
其他的
{
Add(listmapeddatadb.Where(s=>s.ApiCatalog==itemMl.Key)。选择(s=>s.K360Catalog.FirstOrDefault(),itemMl.Value);
}
}
}
var catalogProducts = _context.CatalogProducts.ToList();
foreach (var kp in ListKp)
{
if (!catalogProducts.Any(x => x.Name == kp.Name))
_context.CatalogProducts.Add(kp);
else
{
//Use AutoMapper automatically do the mapping
var config = new MapperConfiguration(cfg => cfg.CreateMap<CatalogProduct, CatalogProduct>().ForMember(c => c.Id, opt => opt.Ignore()));
var oldone = catalogProducts.FirstOrDefault(c => c.Name == kp.Name);
var mapper = config.CreateMapper();
oldone = mapper.Map<CatalogProduct, CatalogProduct>(kp, oldone);
_context.CatalogProducts.Update(oldone);
}
}
Configuration.AutoDetectChangesEnabled = false;
Configuration.ProxyCreationEnabled = false;
_context.Configuration.AutoDetectChangesEnabled = true;
_context.Configuration.ProxyCreationEnabled = true;
// Avoid re-initializing automapper EVERY loop iteration.
var config = new MapperConfiguration(cfg => cfg.CreateMap<CatalogProduct, CatalogProduct>()
.ForMember(c => c.Id, opt => opt.Ignore()));
var mapper = config.CreateMapper();
foreach (var kp in ListKp)
{
var existingCatalogProduct = _context.CatalogProducts.SingleOrDefault(x => x.Name == kp.Name);
if (existingCatalogProduct == null)
_context.CatalogProducts.Add(kp);
else
mapper.Map<CatalogProduct, CatalogProduct>(kp, existingCatalogProduct);
}
// ...
_context.SaveChanges();
var existingCatalogProduct = _context.CatalogProducts
.SingleOrDefault(x => x.Name == kp.Name
&& x.ProductType = kp.ProductType
&& x.Category = kp.Category /*etc*/ );