public static void Run(DbContext db) { if (!db.Set<Profile>().Any()) db.Add(new Profile { Name = "Alexandre Machado", Email = "*****@*****.**", Login = "******" }); if (!db.Set<Skill>().Any()) db.AddRange( new Skill { SkillName = "ASP.NET" }, new Skill { SkillName = "Ruby" }, new Skill { SkillName = "JavaScript" } ); if (!db.Set<Mastery>().Any()) db.AddRange( new Mastery { Code = 10, Name = "Iniciante", Description = "recordação não-situacional, reconhecimento decomposto, decisão analítica, consciência monitorada" }, new Mastery { Code = 20, Name = "Competente", Description = "recordação situacional, reconhecimento decomposto, decisão analítica, consciência monitorada" }, new Mastery { Code = 30, Name = "Proeficiente", Description = "recordação situacional, reconhecimento holítico, decisão analítica, consciência monitorada" }, new Mastery { Code = 40, Name = "Experiente", Description = "recordação situacional, reconhecimento holítico, decisão intuitiva, consciência monitorada" }, new Mastery { Code = 50, Name = "Mestre", Description = "recordação situacional, reconhecimento holítico, decisão intuitiva, consciência absorvida" }); db.SaveChanges(); }
private static void PopulateData(DbContext context, DateTime latestAlbumDate) { var albums = TestAlbumDataProvider.GetAlbums(latestAlbumDate); foreach (var album in albums) { context.Add(album); } context.SaveChanges(); }
static internal protected void addItem <T>(T item, DbContext db) where T : PeriodData { try { db?.Add(item); db?.SaveChanges(); } catch (Exception e) { Log.Exception(e); rollBack(db); try { db?.Update(item); db?.SaveChanges(); } catch (Exception e1) { Log.Exception(e1); rollBack(db); } } }
[Fact] // Issue #3376 public virtual void Can_use_self_referencing_overlapping_FK_PK() { var modelBuilder = CreateModelBuilder(); modelBuilder.Entity<ModifierGroupHeader>() .HasKey(x => new { x.GroupHeaderId, x.AccountId }); modelBuilder.Entity<ModifierGroupHeader>() .HasOne(x => x.ModifierGroupHeader2) .WithMany(x => x.ModifierGroupHeader1) .HasForeignKey(x => new { x.LinkedGroupHeaderId, x.AccountId }); var contextOptions = new DbContextOptionsBuilder() .UseModel(modelBuilder.Model) .UseInMemoryDatabase() .Options; using (var context = new DbContext(contextOptions)) { var parent = context.Add(new ModifierGroupHeader { GroupHeaderId = 77, AccountId = 90 }).Entity; var child1 = context.Add(new ModifierGroupHeader { GroupHeaderId = 78, AccountId = 90 }).Entity; var child2 = context.Add(new ModifierGroupHeader { GroupHeaderId = 79, AccountId = 90 }).Entity; child1.ModifierGroupHeader2 = parent; child2.ModifierGroupHeader2 = parent; context.SaveChanges(); AssertGraph(parent, child1, child2); } using (var context = new DbContext(contextOptions)) { var parent = context.Set<ModifierGroupHeader>().Single(e => e.GroupHeaderId == 77); var child1 = context.Set<ModifierGroupHeader>().Single(e => e.GroupHeaderId == 78); var child2 = context.Set<ModifierGroupHeader>().Single(e => e.GroupHeaderId == 79); AssertGraph(parent, child1, child2); } }
public override void Given() { _data = new TlProviderBuilder().Build(); DbContext.Add(_data); DbContext.SaveChanges(); }
public void Add <TEntity>(TEntity entity) where TEntity : Entity => _dbContext.Add(entity);
public async Task Can_add_update_delete_end_to_end() { var serviceProvider = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .AddSingleton <ILoggerFactory>(new ListLoggerFactory()) .AddSingleton(TestModelSource.GetFactory(OnModelCreating)) .BuildServiceProvider(validateScopes: true); var options = new DbContextOptionsBuilder() .UseInternalServiceProvider(serviceProvider) .UseInMemoryDatabase(nameof(DatabaseInMemoryTest)) .Options; var customer = new Customer { Id = 42, Name = "Theon" }; using (var context = new DbContext(options)) { context.Add(customer); await context.SaveChangesAsync(); customer.Name = "Changed!"; } using (var context = new DbContext(options)) { var customerFromStore = context.Set <Customer>().Single(); Assert.Equal(42, customerFromStore.Id); Assert.Equal("Theon", customerFromStore.Name); } using (var context = new DbContext(options)) { customer.Name = "Theon Greyjoy"; context.Update(customer); await context.SaveChangesAsync(); } using (var context = new DbContext(options)) { var customerFromStore = context.Set <Customer>().Single(); Assert.Equal(42, customerFromStore.Id); Assert.Equal("Theon Greyjoy", customerFromStore.Name); } using (var context = new DbContext(options)) { context.Remove(customer); await context.SaveChangesAsync(); } using (var context = new DbContext(options)) { Assert.Equal(0, context.Set <Customer>().Count()); } }
/// <summary> /// 从OCR接口中 根据规则 获取详细内容 (暂无校验) /// </summary> /// <param name="OcrResult"></param> /// <returns></returns> private static Result RecognitOCRResult(string OcrResult) { try { var OCRResultModel = JsonConvert.DeserializeObject <OCRResult>(OcrResult); var WordList = OCRResultModel.words_result; //被识别的内容 var OCRStoreName = string.Empty; //被识别出来的商铺名称 //查询所有的商铺规则并缓存 List <StoreOCRDetail> AllStoreOCRDetailRuleList = CacheHandle <List <StoreOCRDetail> >( Key: "AllStoreOCRDetailRuleList" , Hour: double.Parse(ConfigurationUtil.GetSection("ObjectConfig:CacheExpiration:AllStoreOCRDetailRuleList")) , sqlWhere: ""); //所有商铺名称规则 var StoreNameRuleList = AllStoreOCRDetailRuleList.Where(s => s.OCRKeyType == (int)OCRKeyType.StoreName).Select(c => c.OCRKey).ToList(); var resultStoreName = FindStoreNameFromAllRule(WordList, StoreNameRuleList);//根据所有的店铺名规则匹配出的StoreName var StoreModel = dal.GetModel <Store>($" and StoreName like '%{resultStoreName}%'"); if (StoreModel == null) { return(new Result(false, "识别商铺名称失败!", "")); } //最后识别结果 var ReceiptOCRModel = new ReceiptOCR { StoreId = StoreModel.StoreId, StoreName = resultStoreName, StoreCode = StoreModel.StoreCode, ReceiptNo = "", TranAmount = 0, TransDatetime = Commom.DefaultDateTime, RecongnizelId = Guid.Empty, Base64 = "" }; //当前店铺的规则明细 var ThisStoreOCRDetail = AllStoreOCRDetailRuleList.Where(s => s.StoreId == StoreModel.StoreId).ToList(); //根据店铺规则明细 关键字类型 关键字 取值方法 匹配识别结果 foreach (var StoreDetailRule in ThisStoreOCRDetail) { for (int i = 0; i < WordList.Count(); i++) { Result ReturnResult = GetValue(WordList, i, StoreDetailRule); //根据规则取值 if (ReturnResult.Success) { var ReturnData = ReturnResult.Data.ToString(); if (!string.IsNullOrWhiteSpace(ReturnData)) { switch (StoreDetailRule.OCRKeyType) //枚举有注释,根据关键字类型赋值 { case (int)OCRKeyType.StoreName: continue; case (int)OCRKeyType.ReceiptNO: if (!string.IsNullOrWhiteSpace(ReturnData) && string.IsNullOrWhiteSpace(ReceiptOCRModel.ReceiptNo)) { ReceiptOCRModel.ReceiptNo = ReturnResult.Data.ToString(); continue; } break; case (int)OCRKeyType.DateTime: if (!string.IsNullOrWhiteSpace(ReturnData) && ReceiptOCRModel.TransDatetime == Commom.DefaultDateTime) { ReturnData = ReturnData.Replace(" ", "").Insert(10, " "); //可能会识别成 2019 - 05 - 1512:14:44 转datetime 报错 if (DateTime.TryParse(ReturnData, out var DateTimeResult)) { ReceiptOCRModel.TransDatetime = DateTimeResult; continue; } } break; case (int)OCRKeyType.Amount: if (!string.IsNullOrWhiteSpace(ReturnData) && ReceiptOCRModel.TranAmount == 0) { if (decimal.TryParse(ReturnResult.Data.ToString(), out var AmountResult)) { ReceiptOCRModel.TranAmount = AmountResult; continue; } } break; default: return(new Result(false, $"商铺未设置该关键字类型取值方法:{StoreDetailRule.OCRKeyType}", null)); } } } } } var RecongnizeModelId = Guid.NewGuid(); var RecongnizeModel = new ApplyPictureRecongnize { id = RecongnizeModelId, applyid = Guid.Empty, Lineno = 0, LineContent = JsonConvert.SerializeObject(WordList), OCRResult = JsonConvert.SerializeObject(ReceiptOCRModel) }; var AddResult = DbContext.Add(RecongnizeModel);//添加原始数据 applyid 等待积分申请 //添加成功后 出参RecongnizeModelId if (AddResult == 0) { ReceiptOCRModel.RecongnizelId = RecongnizeModelId; } else { return(new Result(false, "添加到ApplyPictureRecongnize失败", null)); } return(new Result(true, "识别成功", ReceiptOCRModel)); } catch (Exception ex) { Log.Error("VerifyOCRResult", ex); return(new Result(false, ex.Message, null)); } //同步寻找 string FindStoreNameFromAllRule(List <Words> words, List <string> StoreNameList) { foreach (var Name in StoreNameList) { foreach (var word in words) { if (word.words.Contains(Name)) { return(word.words); } } } return(""); } //异步寻找 async Task <string> FindStoreNameFromAllRuleAsync(List <Words> words, List <string> StoreNameList) { var Sresult = ""; foreach (var names in StoreNameList) { var LineCount = words.Count(); //识别内容数量 //二分异步寻找 var afterLine = LineCount % 2 == 1 ? (LineCount - 1) / 2 : LineCount / 2; //前一半 var beforeLine = LineCount - afterLine; //后一半 CancellationTokenSource ct = new CancellationTokenSource(); for (int i = 0; i < 2; i++) { var min = i % 2 == 0 ? 0 : afterLine; var max = i % 2 == 0 ? afterLine - 1 : LineCount; await Task.Run(() => { for (int j = min; j < max; j++) { if (ct.IsCancellationRequested) { if (words[j].words.Contains(names)) { ct.Cancel(); Sresult = words[j].words; } } } }, ct.Token); } } return(""); } //根据规则获取指定识别内容 Result GetValue(List <Words> words_result, int index, StoreOCRDetail StoreDetailRule) { var WordValue = ""; if (words_result[index].words.Contains(StoreDetailRule.OCRKey)) { switch (StoreDetailRule.GetValueWay)//可查看枚举注释 { case (int)GetValueWay.OCRKey: WordValue = words_result[index].words; break; case (int)GetValueWay.AfterOCRKey: var IndexOfKey = words_result[index].words.IndexOf(StoreDetailRule.OCRKey) + StoreDetailRule.OCRKey.Length + StoreDetailRule.SkipLines; WordValue = words_result[index].words.Substring(IndexOfKey); break; case (int)GetValueWay.NextLine: if (index + StoreDetailRule.SkipLines <= words_result.Count()) { WordValue = words_result[index + StoreDetailRule.SkipLines].words; } break; default: return(new Result(false, $"商铺未设置该关键字取值方法:{StoreDetailRule.GetValueWay}", null)); } } return(new Result(true, "", WordValue)); } }
private void RunCore <TEntity>(DbContext dbContext, IEntityType entityType, ICollection <TEntity> entities, Expression <Func <TEntity, object> >?matchExpression, Expression <Func <TEntity, TEntity, TEntity> >?updateExpression, Expression <Func <TEntity, TEntity, bool> >?updateCondition, RunnerQueryOptions queryOptions) where TEntity : class { // Find matching entities in the dbContext var matches = FindMatches(entityType, entities, dbContext, matchExpression); Action <TEntity, TEntity>? updateAction = null; Func <TEntity, TEntity, bool>?updateTest = updateCondition?.Compile(); if (updateExpression != null) { // If update expression is specified, create an update delegate based on that if (!(updateExpression.Body is MemberInitExpression entityUpdater)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.ArgumentMustBeAnInitialiserOfTheTEntityType, "updater"), nameof(updateExpression)); } var properties = entityUpdater.Bindings.Select(b => b.Member).OfType <PropertyInfo>(); var updateFunc = updateExpression.Compile(); updateAction = (dbEntity, newEntity) => { var tmp = updateFunc(dbEntity, newEntity); foreach (var prop in properties) { var property = entityType.FindProperty(prop.Name); prop.SetValue(dbEntity, prop.GetValue(tmp) ?? property.GetDefaultValue()); } }; } else if (!queryOptions.NoUpdate) { // Otherwise create a default update delegate that updates all non match, non auto generated columns var joinColumns = ProcessMatchExpression(entityType, matchExpression, queryOptions); var properties = entityType.GetProperties() .Where(p => p.ValueGenerated == ValueGenerated.Never) .Select(p => typeof(TEntity).GetProperty(p.Name)) .Where(p => p != null) .Except(joinColumns.Select(c => c.PropertyInfo)); updateAction = (dbEntity, newEntity) => { foreach (var prop in properties) { var property = entityType.FindProperty(prop.Name); prop.SetValue(dbEntity, prop.GetValue(newEntity) ?? property.GetDefaultValue()); } }; } foreach (var(dbEntity, newEntity) in matches) { if (dbEntity == null) { foreach (var prop in typeof(TEntity).GetProperties()) { if (prop.GetValue(newEntity) == null) { var property = entityType.FindProperty(prop.Name); if (property != null) { var defaultValue = property.GetDefaultValue(); if (defaultValue != null) { prop.SetValue(newEntity, defaultValue); } } } } dbContext.Add(newEntity); continue; } if (updateTest?.Invoke(dbEntity, newEntity) == false) { continue; } updateAction?.Invoke(dbEntity, newEntity); } }
public async Task Can_add_update_delete_end_to_end_using_partial_shadow_state() { var model = new Model(); var customerType = model.AddEntityType(typeof(Customer)); customerType.GetOrSetPrimaryKey(customerType.GetOrAddProperty("Id", typeof(int))); customerType.GetOrAddProperty("Name", typeof(string), shadowProperty: true); var optionsBuilder = new EntityOptionsBuilder() .UseModel(model); optionsBuilder.UseInMemoryStore(); var customer = new Customer { Id = 42 }; using (var context = new DbContext(_fixture.ServiceProvider, optionsBuilder.Options)) { context.Add(customer); // TODO: Better API for shadow state access var customerEntry = ((IAccessor <InternalEntityEntry>)context.Entry(customer)).Service; customerEntry[customerType.GetProperty("Name")] = "Daenerys"; await context.SaveChangesAsync(); customerEntry[customerType.GetProperty("Name")] = "Changed!"; } using (var context = new DbContext(_fixture.ServiceProvider, optionsBuilder.Options)) { var customerFromStore = context.Set <Customer>().Single(); Assert.Equal(42, customerFromStore.Id); Assert.Equal( "Daenerys", (string)context.Entry(customerFromStore).Property("Name").CurrentValue); } using (var context = new DbContext(_fixture.ServiceProvider, optionsBuilder.Options)) { var customerEntry = ((IAccessor <InternalEntityEntry>)context.Entry(customer)).Service; customerEntry[customerType.GetProperty("Name")] = "Daenerys Targaryen"; context.Update(customer); await context.SaveChangesAsync(); } using (var context = new DbContext(_fixture.ServiceProvider, optionsBuilder.Options)) { var customerFromStore = context.Set <Customer>().Single(); Assert.Equal(42, customerFromStore.Id); Assert.Equal( "Daenerys Targaryen", (string)context.Entry(customerFromStore).Property("Name").CurrentValue); } using (var context = new DbContext(_fixture.ServiceProvider, optionsBuilder.Options)) { context.Remove(customer); await context.SaveChangesAsync(); } using (var context = new DbContext(_fixture.ServiceProvider, optionsBuilder.Options)) { Assert.Equal(0, context.Set <Customer>().Count()); } }
public void Create(T entity) { _dbContext.Add(entity); }
public void CreateSong(Song Entity) { DbContext.Add(Entity); DbContext.SaveChanges(); }
public int Add(T entity) { _dbContext.Add(entity); return(_dbContext.SaveChanges()); }
public void Create(T entity) { _db.Add(entity); }
public static void InsertGraph(DbContext context, object rootEntity) { context.Add(rootEntity); context.SaveChanges(); }
public static void Insert(DbContext context, object entity) { context.Add(entity); context.SaveChanges(); }
private static void FixupTest(IModel model) { var optionsBuilder = new DbContextOptionsBuilder() .UseModel(model); optionsBuilder.UseInMemoryStore(persist: false); using (var context = new DbContext(optionsBuilder.Options)) { var guid1 = Guid.NewGuid(); var guid2 = Guid.NewGuid(); var guid3 = Guid.NewGuid(); context.Add(new KoolEntity1 { Id1 = 11, Id2 = guid1, KoolEntity2Id = 24 }); context.Add(new KoolEntity1 { Id1 = 12, Id2 = guid2, KoolEntity2Id = 24 }); context.Add(new KoolEntity1 { Id1 = 13, Id2 = guid3, KoolEntity2Id = 25 }); context.Add(new KoolEntity2 { Id = 21, KoolEntity1Id1 = 11, KoolEntity1Id2 = guid1, KoolEntity3Id = 33 }); context.Add(new KoolEntity2 { Id = 22, KoolEntity1Id1 = 11, KoolEntity1Id2 = guid1, KoolEntity3Id = 33 }); context.Add(new KoolEntity2 { Id = 23, KoolEntity1Id1 = 11, KoolEntity1Id2 = guid1, KoolEntity3Id = 35 }); context.Add(new KoolEntity2 { Id = 24, KoolEntity1Id1 = 12, KoolEntity1Id2 = guid2, KoolEntity3Id = 35 }); context.Add(new KoolEntity2 { Id = 25, KoolEntity1Id1 = 12, KoolEntity1Id2 = guid2, KoolEntity3Id = 35 }); context.Add(new KoolEntity3 { Id = 31 }); context.Add(new KoolEntity3 { Id = 32 }); context.Add(new KoolEntity3 { Id = 33 }); context.Add(new KoolEntity3 { Id = 34 }); context.Add(new KoolEntity3 { Id = 35 }); Assert.Equal(3, context.ChangeTracker.Entries<KoolEntity1>().Count()); Assert.Equal(5, context.ChangeTracker.Entries<KoolEntity2>().Count()); Assert.Equal(5, context.ChangeTracker.Entries<KoolEntity3>().Count()); foreach (var entry in context.ChangeTracker.Entries<KoolEntity1>()) { var entity = entry.Entity; Assert.Equal(entity.KoolEntity2Id, entity.NavTo2.Id); Assert.Contains(entity, entity.NavTo2.NavTo1s); } foreach (var entry in context.ChangeTracker.Entries<KoolEntity2>()) { var entity = entry.Entity; // TODO: This broke after removing IForeignKey.ReferencingProperties //Assert.Equal(entity.KoolEntity1Id1, entity.NavTo1.Id1); //Assert.Equal(entity.KoolEntity1Id2, entity.NavTo1.Id2); //Assert.Contains(entity, entity.NavTo1.NavTo2s); } } }
private static void PopulateDataForEventSignup(DbContext context) { if (!populatedData) { var campaignEvents = TestEventModelProvider.GetEvents(); foreach (var campaignEvent in campaignEvents) { context.Add(campaignEvent); context.Add(campaignEvent.Campaign); } context.SaveChanges(); populatedData = true; } }
public async Task HandleAsync(CreateContactCommand command) { _dbContext.Add(command.Contact); await _dbContext.SaveChangesAsync(); }
public TEntidade Adicionar(TEntidade entidade) { var entity = _context.Add <TEntidade>(entidade); return(entity.Entity); }
public TAggregateRoot AddAndReturn(TAggregateRoot aggregateRoot) => DbContext.Add(aggregateRoot).Entity;
public void Add(TAggregateRoot aggregateRoot) => DbContext.Add(aggregateRoot);
public async Task <ISingleResponse <OrderHeader> > CreateOrderAsync(OrderHeader header, OrderDetail[] details) { Logger?.LogDebug("{0} has been invoked", nameof(CreateOrderAsync)); var response = new SingleResponse <OrderHeader>(); // Begin transaction using (var transaction = await DbContext.Database.BeginTransactionAsync()) { try { // todo: Retrieve available warehouse to dispatch products var warehouses = await DbContext.Warehouses.ToListAsync(); foreach (var detail in details) { // Retrieve product by id var product = await DbContext.GetProductAsync(new Product(detail.ProductID)); // Throw exception if product no exists if (product == null) { throw new NonExistingProductException(string.Format(SalesDisplays.NonExistingProductExceptionMessage, detail.ProductID)); } // Throw exception if product is discontinued if (product.Discontinued == true) { throw new AddOrderWithDiscontinuedProductException(string.Format(SalesDisplays.AddOrderWithDiscontinuedProductExceptionMessage, product.ProductID)); } // Throw exception if quantity for product is invalid if (detail.Quantity <= 0) { throw new InvalidQuantityException(string.Format(SalesDisplays.InvalidQuantityExceptionMessage, product.ProductID)); } // Set values for detail detail.ProductName = product.ProductName; detail.UnitPrice = product.UnitPrice; detail.Total = product.UnitPrice * detail.Quantity; } // Set default values for order header if (!header.OrderDate.HasValue) { header.OrderDate = DateTime.Now; } header.OrderStatusID = 100; // Calculate total for order header from order's details header.Total = details.Sum(item => item.Total); header.DetailsCount = details.Count(); // Save order header DbContext.Add(header, UserInfo); await DbContext.SaveChangesAsync(); foreach (var detail in details) { // Set order id for order detail detail.OrderHeaderID = header.OrderHeaderID; detail.CreationUser = header.CreationUser; // Add order detail DbContext.Add(detail, UserInfo); await DbContext.SaveChangesAsync(); // Create product inventory instance var productInventory = new ProductInventory { ProductID = detail.ProductID, LocationID = warehouses.First().LocationID, OrderDetailID = detail.OrderDetailID, Quantity = detail.Quantity * -1, CreationUser = header.CreationUser, CreationDateTime = DateTime.Now }; // Save product inventory DbContext.Add(productInventory); } await DbContext.SaveChangesAsync(); response.Model = header; // Commit transaction transaction.Commit(); Logger.LogInformation(SalesDisplays.CreateOrderMessage); } catch (Exception ex) { response.SetError(Logger, nameof(CreateOrderAsync), ex); } } return(response); }
public override EntityEntry <TEntity> Add(TEntity entity) => _context.Add(entity);
public void Add(T entity) { _context.Add(entity); }
/// <summary> /// 创建积分申请单,校验信息成功并推送 /// 若原先存在积分申请单,失败的原因:校验失败 所有应该重新赋值 /// </summary> /// <param name="applyPointRequest"></param> /// <returns></returns> public static Result CreateApplyPoint(ApplyPointRequest applyPointRequest) { try { #region 图片上传 ImageResponse ImageResponse = null; try { var FileUploadResult = ImageUpload(Commom.FileUploadUrl, applyPointRequest.receiptOCR.Base64); if (!FileUploadResult.Success) { return(FileUploadResult); } ImageResponse = JsonConvert.DeserializeObject <ImageResponse>(FileUploadResult.Data.ToString()); } catch (Exception ex) { Log.Error("CreateApplyPoint-FileUpload", ex); return(new Result(false, ex.Message, null)); } #endregion Store StoreModel = CacheHandle <Store>( Key: $"Store{applyPointRequest.receiptOCR.StoreId}", Hour: double.Parse(ConfigurationUtil.GetSection("ObjectConfig:CacheExpiration:Store")), sqlWhere: $" and StoreId = '{applyPointRequest.receiptOCR.StoreId}'"); StoreOCR StoreOCRRule = CacheHandle <StoreOCR>( Key: $"StoreOCR{applyPointRequest.receiptOCR.StoreId}", Hour: double.Parse(ConfigurationUtil.GetSection("ObjectConfig:CacheExpiration:StoreOCR")), sqlWhere: $"and StoreId = '{applyPointRequest.receiptOCR.StoreId}'"); var ApplyPoint = dal.GetModel <ApplyPoint>($" and ReceiptNo='{applyPointRequest.receiptOCR.ReceiptNo}' and StoreID='{applyPointRequest.receiptOCR.StoreId}'"); ApplyPictureRecongnize applyPictureRecongnize = dal.GetModel <ApplyPictureRecongnize>($" and id='{applyPointRequest.receiptOCR.RecongnizelId}'"); var IsHas = false; // 是否原先存在积分申请单 默认没有 更新识别原始表 if (ApplyPoint == null) //判断该小票号 是否存在积分申请单 不存在则添加原始积分申请单 (已解析原始数据,校验失败) { var ApplyPointId = Guid.NewGuid(); ApplyPoint = new ApplyPoint { ApplyPointID = ApplyPointId, MallID = StoreModel.MallID, StoreID = applyPointRequest.receiptOCR.StoreId, CardID = Guid.Parse(applyPointRequest.cardId), ReceiptNo = applyPointRequest.receiptOCR.ReceiptNo, TransDate = applyPointRequest.receiptOCR.TransDatetime, TransAmt = applyPointRequest.receiptOCR.TranAmount, VerifyStatus = StoreOCRRule.needVerify == 0 ? 1 : 0, ReceiptPhoto = ImageResponse.fileURL }; applyPictureRecongnize.applyid = ApplyPointId; DbContext.Update <ApplyPictureRecongnize>(applyPictureRecongnize); } else { IsHas = true; ApplyPoint.MallID = StoreModel.MallID; ApplyPoint.StoreID = applyPointRequest.receiptOCR.StoreId; ApplyPoint.CardID = Guid.Parse(applyPointRequest.cardId); ApplyPoint.ReceiptNo = applyPointRequest.receiptOCR.ReceiptNo; ApplyPoint.TransDate = applyPointRequest.receiptOCR.TransDatetime; ApplyPoint.TransAmt = applyPointRequest.receiptOCR.TranAmount; ApplyPoint.VerifyStatus = StoreOCRRule.needVerify == 0 ? 1 : 0; } var VerifyRecognitionResult = VerifyRecognition(applyPointRequest.receiptOCR); //校验结果 ApplyPoint.AuditDate = DateTime.Now; if (VerifyRecognitionResult.Success) //校验成功 { ApplyPoint.RecongizeStatus = 2; ApplyPoint.VerifyStatus = 1; } else//校验失败 修改值 { ApplyPoint.RecongizeStatus = 3; ApplyPoint.VerifyStatus = 0; ApplyPoint.Status = 0; if (IsHas) { DbContext.Update <ApplyPoint>(ApplyPoint); } else { DbContext.Add <ApplyPoint>(ApplyPoint); } return(VerifyRecognitionResult); } var LastRes = true;//添加是否成功 if (IsHas) { if (!DbContext.Update <ApplyPoint>(ApplyPoint)) { LastRes = false; } } else { if (DbContext.Add <ApplyPoint>(ApplyPoint) != 0) { LastRes = false; } } if (LastRes) { List <Company> companyList = CacheHandle <List <Company> >( Key: "Company", Hour: double.Parse(ConfigurationUtil.GetSection("ObjectConfig:CacheExpiration:Company")), sqlWhere: ""); List <OrgInfo> orgList = CacheHandle <List <OrgInfo> >( Key: "OrgInfo", Hour: double.Parse(ConfigurationUtil.GetSection("ObjectConfig:CacheExpiration:OrgInfo")), sqlWhere: ""); //自动积分 推送 var arg = new WebPosArg { companyID = companyList.Where(s => s.CompanyId == StoreModel.CompanyID).FirstOrDefault()?.CompanyCode ?? "", storeID = StoreModel.StoreCode, cardID = dal.GetModel <Card>($" and CardID='{applyPointRequest.cardId}'")?.CardCode ?? "", cashierID = "CrmApplyPoint", discountPercentage = 0, orgID = orgList.Where(s => s.OrgId == StoreModel.OrgID).FirstOrDefault()?.OrgCode ?? "", receiptNo = applyPointRequest.receiptOCR.ReceiptNo, txnDateTime = applyPointRequest.receiptOCR.TransDatetime }; var argStr = JsonConvert.SerializeObject(arg); ProducerMQ(argStr); return(new Result(true, "校验成功,已申请积分!", null)); } return(new Result(false, "校验成功,对ApplyPoint操作失败!", null)); } catch (Exception ex) { Log.Error("CreateApplyPoint", ex); return(new Result(false, ex.Message, null)); } }
public ActionResult <Iso8583RouterComm> Create([FromBody] Iso8583RouterComm obj) { entityManager.Add(obj); entityManager.SaveChanges(); return(obj); }
private static object _chatCreationLocker = new object();//todo: low I don't like it's static, but i don't understand now where should lock be kept public static DatabaseState GetRootState(BotFlow.Persistance.UserInChat userInChat, string connectionString) { var db = new DbContext(connectionString); var userInChatPersistance = db.UsersInChat.GetUserInChatPersistance(userInChat); List <FlowState> flowStates; if (userInChatPersistance == null) { var userId = userInChat.UserId; uint lastLanguage = 0; if (db.UsersInChat.Any()) { var maxId = db.UsersInChat.Max(uic => uic.Id); lastLanguage = db.UsersInChat.Single(uc => uc.Id == maxId).ChatInTelegram.LanguageIndex; } lock (_chatCreationLocker)//todo: low Not the fastest lock { var chatInTelegram = db.ChatInTelegrams.ById(userInChat.ChatId) ?? new ChatInTelegram { Id = userInChat.ChatId, LanguageIndex = /*todo: low I don't understand where it should be in this case*/ LocalizedStrings.Language = lastLanguage }; var userInTelegram = db.UserInTelegrams.ById(userId) ?? new UserInTelegram { Id = userId, }; userInChatPersistance = new UserInChat { ChatInTelegram = chatInTelegram, UserInTelegram = userInTelegram, }; db.Add(userInChatPersistance); var firstFlowState = new FlowState { UserInChat = userInChatPersistance, FlowStateId = string.Empty }; db.Add(firstFlowState); userInChatPersistance.FlowStates.Add(firstFlowState); db.SaveChanges(); db.Refresh(RefreshMode.OverwriteChangesFromStore, userInChat); flowStates = new List <FlowState> { firstFlowState }; } } else { flowStates = new List <FlowState>(userInChatPersistance.FlowStates.ToArray()); //предполагаем, что у созданного сходу есть один стейт } return(new DatabaseState(0, flowStates, db, userInChatPersistance)); }
public void Create(T entity) { _context.Add <T>(entity); }
public void Add(TEntity entity) { _dbContext.Add(entity); }
public static void AddOrUpdateSeed <T>(this DbContext context, Func <T, T, bool> predicate = null, params T[] entities) where T : class, IHasId { if (entities.Any(r => r.Id == 0) && entities.Any(r => r.Id != 0)) { throw new ArgumentException(nameof(entities)); } var idsFilled = entities.Any(r => r.Id != 0); if (!idsFilled && predicate == null) { throw new ArgumentException(nameof(predicate)); } IEnumerable <T> existingEntities; if (predicate == null) { predicate = (r, e) => e.Id == r.Id; existingEntities = context.Set <T>().Where(r => entities.Any(e => e.Id == r.Id)).ToList(); } else { existingEntities = context.Set <T>().ToList().Where(r => entities.Any(e => predicate(r, e))).ToList(); } foreach (var entity in entities) { var existingEntity = existingEntities.FirstOrDefault(r => predicate(r, entity)); if (existingEntity == null) { context.Add(entity); } else { entity.CopySimplePropertiesTo(existingEntity, false, false); } } if (context.ChangeTracker.Entries().Any(r => r.State != EntityState.Unchanged)) { context.Database.OpenConnection(); try { if (idsFilled) { context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [" + typeof(T).Name + "] ON"); } } catch (Exception ex) { //TODO //var log = LogManager.GetLogger(typeof(EfHelper)); //log.Debug("SET IDENTITY_INSERT [" + typeof(T).Name + "] ON is failed:\n" + ex); } context.SaveChanges(); context.Database.CloseConnection(); } }
[Fact] // Issue #3376 public virtual void Can_use_self_referencing_overlapping_FK_PK() { var modelBuilder = CreateModelBuilder(); modelBuilder.Entity<Node>(b => { b.HasKey(e => new { e.ListId, e.PreviousNodeId }); b.HasOne(e => e.NextNode) .WithOne(e => e.PreviousNode) .HasForeignKey<Node>(e => new { e.ListId, e.NextNodeId }); }); var contextOptions = new DbContextOptionsBuilder() .UseModel(modelBuilder.Model) .UseInMemoryDatabase() .Options; using (var context = new DbContext(contextOptions)) { var node1 = context.Add(new Node { ListId = 90, PreviousNodeId = 77 }).Entity; var node2 = context.Add(new Node { ListId = 90, PreviousNodeId = 78 }).Entity; var node3 = context.Add(new Node { ListId = 90, PreviousNodeId = 79 }).Entity; node1.NextNode = node2; node3.PreviousNode = node2; context.SaveChanges(); AssertGraph(node1, node2, node3); } using (var context = new DbContext(contextOptions)) { var node1 = context.Set<Node>().Single(e => e.PreviousNodeId == 77); var node2 = context.Set<Node>().Single(e => e.PreviousNodeId == 78); var node3 = context.Set<Node>().Single(e => e.PreviousNodeId == 79); AssertGraph(node1, node2, node3); } }
public void Insert(T parameter) { _currentDbContext.Add(parameter); _currentDbContext.SaveChanges(); }
private void PopulateData(DbContext context) { if (!populatedData) { var activities = TestActivityModelProvider.GetActivities(); foreach (var activity in activities) { context.Add(activity); context.Add(activity.Campaign); activitiesAdded++; } context.SaveChanges(); populatedData = true; } }
public static async Task Seed(DbContext db) { var user = new User { UserId = "mladen" }; var wallet = new UserWallet { Currency = "HRK", MoneyAmmount = 500, UserId = user.UserId }; db.AddRange(user, wallet); var hajduk = NewFootballTeam("Hajduk"); var dinamo = NewFootballTeam("Dinamo"); var barca = NewFootballTeam("Barcelona"); var arsenal = NewFootballTeam("Arsenal"); db.AddRange(hajduk, dinamo, barca, arsenal); var hajdukVsDinamo = new BetablePair { Team1 = hajduk, Team2 = dinamo, Team1WinQuota = 2, Team2WinQuota = 3, DrawQuota = 2.5m }; var barcaVsArsenal = new BetablePair { Team1 = barca, Team2 = arsenal, Team1WinQuota = 2, Team2WinQuota = 3.1m, DrawQuota = 2.4m }; db.AddRange(hajdukVsDinamo, barcaVsArsenal); var ticket = new Ticket { UserId = user.UserId, BetedPairs = new [] { new BetedPair { BetablePair = hajdukVsDinamo, BetablePairId = hajdukVsDinamo.Id, BetedType = BetingType.Draw, }, new BetedPair { BetablePair = barcaVsArsenal, BetablePairId = barcaVsArsenal.Id, BetedType = BetingType.Team1Win, } } }; ticket.Quota = ticket.BetedPairs.Select(p => p.GetQuota()).Product(); db.Add(ticket); await db.SaveChangesAsync(); }
public void Navigation_fixup_happens_with_compiled_metadata_using_non_standard_collection_access() { var optionsBuilder = new DbContextOptionsBuilder() .UseModel(new _OneTwoThreeContextModel()); optionsBuilder.UseInMemoryStore(); using (var context = new DbContext(optionsBuilder.Options)) { context.Add(new KoolEntity6 { Id = 11, Kool5Id = 24 }); context.Add(new KoolEntity5 { Id = 21 }); context.Add(new KoolEntity6 { Id = 12, Kool5Id = 24 }); context.Add(new KoolEntity5 { Id = 22 }); context.Add(new KoolEntity5 { Id = 23 }); context.Add(new KoolEntity6 { Id = 13, Kool5Id = 25 }); context.Add(new KoolEntity5 { Id = 24 }); context.Add(new KoolEntity5 { Id = 25 }); Assert.Equal(3, context.ChangeTracker.Entries<KoolEntity6>().Count()); Assert.Equal(5, context.ChangeTracker.Entries<KoolEntity5>().Count()); foreach (var entry in context.ChangeTracker.Entries<KoolEntity6>()) { var entity = entry.Entity; Assert.Equal(entity.Kool5Id, entity.Kool5.Id); Assert.Contains(entity, entity.Kool5.Kool6s); } } }
private static void FixupTest(IModel model) { var options = new DbContextOptions() .UseModel(model) .UseInMemoryStore(persist: false); using (var context = new DbContext(options)) { var guid1 = Guid.NewGuid(); var guid2 = Guid.NewGuid(); var guid3 = Guid.NewGuid(); context.Add(new KoolEntity1 { Id1 = 11, Id2 = guid1, KoolEntity2Id = 24 }); context.Add(new KoolEntity1 { Id1 = 12, Id2 = guid2, KoolEntity2Id = 24 }); context.Add(new KoolEntity1 { Id1 = 13, Id2 = guid3, KoolEntity2Id = 25 }); context.Add(new KoolEntity2 { Id = 21, KoolEntity1Id1 = 11, KoolEntity1Id2 = guid1, KoolEntity3Id = 33 }); context.Add(new KoolEntity2 { Id = 22, KoolEntity1Id1 = 11, KoolEntity1Id2 = guid1, KoolEntity3Id = 33 }); context.Add(new KoolEntity2 { Id = 23, KoolEntity1Id1 = 11, KoolEntity1Id2 = guid1, KoolEntity3Id = 35 }); context.Add(new KoolEntity2 { Id = 24, KoolEntity1Id1 = 12, KoolEntity1Id2 = guid2, KoolEntity3Id = 35 }); context.Add(new KoolEntity2 { Id = 25, KoolEntity1Id1 = 12, KoolEntity1Id2 = guid2, KoolEntity3Id = 35 }); context.Add(new KoolEntity3 { Id = 31 }); context.Add(new KoolEntity3 { Id = 32 }); context.Add(new KoolEntity3 { Id = 33 }); context.Add(new KoolEntity3 { Id = 34 }); context.Add(new KoolEntity3 { Id = 35 }); Assert.Equal(3, context.ChangeTracker.Entries <KoolEntity1>().Count()); Assert.Equal(5, context.ChangeTracker.Entries <KoolEntity2>().Count()); Assert.Equal(5, context.ChangeTracker.Entries <KoolEntity3>().Count()); foreach (var entry in context.ChangeTracker.Entries <KoolEntity1>()) { var entity = entry.Entity; Assert.Equal(entity.KoolEntity2Id, entity.NavTo2.Id); Assert.Contains(entity, entity.NavTo2.NavTo1s); } foreach (var entry in context.ChangeTracker.Entries <KoolEntity2>()) { var entity = entry.Entity; Assert.Equal(entity.KoolEntity1Id1, entity.NavTo1.Id1); Assert.Equal(entity.KoolEntity1Id2, entity.NavTo1.Id2); Assert.Contains(entity, entity.NavTo1.NavTo2s); } } }
public async void It_throws_object_disposed_exception() { var context = new DbContext(new DbContextOptions<DbContext>()); context.Dispose(); // methods (tests all paths) Assert.Throws<ObjectDisposedException>(() => context.Add(new object())); Assert.Throws<ObjectDisposedException>(() => context.Attach(new object())); Assert.Throws<ObjectDisposedException>(() => context.Update(new object())); Assert.Throws<ObjectDisposedException>(() => context.Remove(new object())); Assert.Throws<ObjectDisposedException>(() => context.SaveChanges()); await Assert.ThrowsAsync<ObjectDisposedException>(() => context.SaveChangesAsync()); var methodCount = typeof(DbContext).GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).Count(); var expectedMethodCount = 27; Assert.True( methodCount == expectedMethodCount, userMessage: $"Expected {expectedMethodCount} methods on DbContext but found {methodCount}. " + "Update test to ensure all methods throw ObjectDisposedException after dispose."); // getters Assert.Throws<ObjectDisposedException>(() => context.ChangeTracker); Assert.Throws<ObjectDisposedException>(() => context.Model); var expectedProperties = new List<string> { "ChangeTracker", "Database", "Model" }; Assert.True(expectedProperties.SequenceEqual( typeof(DbContext) .GetProperties() .Select(p => p.Name) .OrderBy(s => s) .ToList()), userMessage: "Unexpected properties on DbContext. " + "Update test to ensure all getters throw ObjectDisposedException after dispose."); Assert.Throws<ObjectDisposedException>(() => ((IInfrastructure<IServiceProvider>)context).Instance); }
public bool Add(Area entity) { dbContext.Add(entity); return(true); }
public async Task Can_add_update_delete_end_to_end_using_partial_shadow_state() { var model = new Model(); var customerType = new EntityType(typeof(Customer)); customerType.SetKey(customerType.AddProperty("Id", typeof(int), shadowProperty: false, concurrencyToken: false)); customerType.AddProperty("Name", typeof(string), shadowProperty: true, concurrencyToken: false); model.AddEntityType(customerType); var options = new DbContextOptions() .UseModel(model) .UseInMemoryStore(); var customer = new Customer { Id = 42 }; using (var context = new DbContext(options)) { context.Add(customer); // TODO: Better API for shadow state access var customerEntry = context.ChangeTracker.Entry(customer).StateEntry; customerEntry[customerType.GetProperty("Name")] = "Daenerys"; await context.SaveChangesAsync(); customerEntry[customerType.GetProperty("Name")] = "Changed!"; } using (var context = new DbContext(options)) { var customerFromStore = context.Set<Customer>().Single(); Assert.Equal(42, customerFromStore.Id); Assert.Equal( "Daenerys", (string)context.ChangeTracker.Entry(customerFromStore).Property("Name").CurrentValue); } using (var context = new DbContext(options)) { var customerEntry = context.ChangeTracker.Entry(customer).StateEntry; customerEntry[customerType.GetProperty("Name")] = "Daenerys Targaryen"; context.Update(customer); await context.SaveChangesAsync(); } using (var context = new DbContext(options)) { var customerFromStore = context.Set<Customer>().Single(); Assert.Equal(42, customerFromStore.Id); Assert.Equal( "Daenerys Targaryen", (string)context.ChangeTracker.Entry(customerFromStore).Property("Name").CurrentValue); } using (var context = new DbContext(options)) { context.Delete(customer); await context.SaveChangesAsync(); } using (var context = new DbContext(options)) { Assert.Equal(0, context.Set<Customer>().Count()); } }