public virtual IEnumerable <T> Intersect(IEnumerable <T> source) { using (var db = new DbContextWrapper()) { return(db.Context.Set <T>().Intersect(source)); } }
public virtual IList <T> All() { using (var db = new DbContextWrapper()) { return(db.Context.Set <T>().ToList()); } }
public virtual T Find(int id) { using (var db = new DbContextWrapper()) { return(db.Context.Set <T>().FirstOrDefault(x => x.Id == id)); } }
public Tag Find(string value) { value = value.Trim(); using (var db = new DbContextWrapper()) { return(db.Context.Tags.FirstOrDefault(x => x.Title == value)); } }
public override void AddOrUpdate(Tag entity) { using (var db = new DbContextWrapper()) { var dbEntity = db.Context.Tags.FirstOrDefault(x => x.Title == entity.Title); if (dbEntity == null) { db.Context.Entry(entity).State = EntityState.Added; } else { db.Context.Entry(dbEntity).State = EntityState.Detached; } } }
/// <summary> /// Load all ILCD data types in directory. /// </summary> /// <param name="dirName">Full path name of directory</param> /// <param name="ilcdSourceName">Name of ILCD data source</param> /// <param name="dbContext">Shared instance of DbContextWrapper</param> public void LoadAll(string dirName, string ilcdSourceName, DbContextWrapper dbContext, bool isPrivate) { if (dbContext.CreateDataSource(dirName, ilcdSourceName, isPrivate) != null) { // Improve load performance by disabling AutoDetectChanges. dbContext.SetAutoDetectChanges(false); LoadDataType(Path.Combine(dirName, "unitgroups"), dbContext); LoadDataType(Path.Combine(dirName, "flowproperties"), dbContext); LoadDataType(Path.Combine(dirName, "flows"), dbContext); LoadDataType(Path.Combine(dirName, "LCIAmethods"), dbContext); LoadDataType(Path.Combine(dirName, "processes"), dbContext); LoadDataType(Path.Combine(dirName, "sources"), dbContext); LoadDataType(Path.Combine(dirName, "contacts"), dbContext); dbContext.SetAutoDetectChanges(true); } }
public virtual void AddOrUpdate(T entity) { using (var db = new DbContextWrapper()) { var dbEntity = db.Context.Set <T>().FirstOrDefault(x => x.Id == entity.Id); if (dbEntity == null) { db.Context.Entry(entity).State = EntityState.Added; } else { db.Context.Entry(dbEntity).State = EntityState.Detached; db.Context.Entry(entity).State = EntityState.Modified; } } }
/// <summary> /// Load XML files in ILCD data type directory /// </summary> /// <param name="dirName">Full path name of directory for the data type</param> /// <param name="dbContext">Instance of DbContextWrapper</param> public void LoadDataType(string dirName, DbContextWrapper dbContext) { int importCounter = 0; if (Directory.Exists(dirName)) { Program.Logger.InfoFormat("Load {0}...", dirName); string[] files = Directory.GetFiles(dirName, "*.xml"); foreach (string s in files) { Program.Logger.DebugFormat("Load {0}", s); _IlcdData.LoadedDocument = XDocument.Load(s); if (_IlcdData.Save(dbContext)) { importCounter++; } else { Program.Logger.WarnFormat("Data in file {0} was not imported.", s); } } Program.Logger.InfoFormat("{0} of {1} files imported from {2}.", importCounter, files.Length, dirName); } else { Program.Logger.WarnFormat("ILCD data type folder, {0}, does not exist.", dirName); } }
/// <summary> /// Import data from loaded unitgroup file to new UnitGroup entity /// </summary> /// <param name="ilcdDb">Database context wrapper object</param> /// <returns>true iff data was imported</returns> private bool SaveUnitGroup(DbContextWrapper ilcdDb) { bool isSaved = false; string dataSetInternalID = "0"; string uuid = GetCommonUUID(); if (!ilcdDb.IlcdEntityAlreadyExists<UnitGroup>(uuid)) { UnitGroup unitGroup = new UnitGroup(); SaveIlcdEntity(ilcdDb, unitGroup, DataTypeEnum.UnitGroup); unitGroup.Name = GetCommonName(); // Get Reference Flow Property dataSetInternalID = GetElementValue(ElementName("referenceToReferenceUnit")); if (ilcdDb.AddIlcdEntity(unitGroup, uuid)) { ilcdDb.AddEntities<UnitConversion>(CreateUnitConversionList(unitGroup, dataSetInternalID)); isSaved = true; } } return isSaved; }
private bool SaveProcess(DbContextWrapper ilcdDb) { bool isSaved = false; string lookupName; string uuid = GetCommonUUID(); string version = GetCommonVersion(); if (!ilcdDb.IlcdEntityAlreadyExists<LcaDataModel.Process>(uuid, version)) { Program.Logger.InfoFormat("Importing process with uuid {0}", uuid); LcaDataModel.Process process = new LcaDataModel.Process(); SaveIlcdEntity(ilcdDb, process, DataTypeEnum.Process); process.Name = GetElementValue(ElementName("baseName")); process.ReferenceYear = GetElementValue(_CommonNamespace + "referenceYear"); string geog = GetElementAttributeValue(ElementName("locationOfOperationSupplyOrProduction"), "location"); if (geog.Length > 15) geog = geog.Substring(0, 15); process.Geography = geog; lookupName = GetElementAttributeValue(ElementName("quantitativeReference"), "type"); if (lookupName != null) { process.ReferenceTypeID = ilcdDb.LookupEntityID<ReferenceType>(lookupName); } lookupName = GetElementValue(ElementName("typeOfDataSet")); if (lookupName != null) { process.ProcessTypeID = ilcdDb.LookupEntityID<ProcessType>(lookupName); } if (ilcdDb.AddIlcdEntity(process, uuid, version)) { List<ProcessFlow> pfList = LoadedDocument.Root.Descendants(ElementName("exchanges")).Elements(ElementName("exchange")).Select(f => CreateProcessFlow(ilcdDb, f, process.ID)).ToList(); ilcdDb.AddEntities<ProcessFlow>(pfList); isSaved = true; } } return isSaved; }
private ILCDEntity SaveIlcdStub(DbContextWrapper ilcdDb, DataTypeEnum dtEnum) { ILCDEntity ilcdEntity = new ILCDEntity(); ilcdEntity.UUID = GetCommonUUID(); ilcdEntity.Version = GetCommonVersion(); ilcdEntity.DataTypeID = Convert.ToInt32(dtEnum); ilcdEntity.DataSourceID = ilcdDb.GetCurrentIlcdDataSourceID(); return ilcdEntity; }
/// <summary> /// Import data from loaded flow file to new Flow entity /// </summary> /// <param name="ilcdDb">Database context wrapper object</param> /// <returns>true iff data was imported</returns> private bool SaveFlow(DbContextWrapper ilcdDb) { bool isSaved = false; int? fpID; string dataSetInternalID = "0"; string uuid = GetCommonUUID(); int flowId = 0; if (ilcdDb.IlcdEntityAlreadyExists<Flow>(uuid)) ilcdDb.FindRefIlcdEntityID<Flow>(uuid, out flowId); else { XElement fpElement; Flow flow = new Flow(); SaveIlcdEntity(ilcdDb, flow, DataTypeEnum.Flow); // TODO : generate name from classification/category flow.Name = GetElementValue(ElementName("baseName")); flow.CASNumber = GetElementValue(ElementName("CASNumber")); flow.FlowTypeID = ilcdDb.GetFlowTypeID(GetElementValue(ElementName("typeOfDataSet"))); // Get Reference Flow Property dataSetInternalID = GetElementValue(ElementName("referenceToReferenceFlowProperty")); fpElement = GetElementWithInternalId(ElementName("flowProperty"), dataSetInternalID); fpID = GetFlowPropertyID(ilcdDb, fpElement); flow.ReferenceFlowProperty = (int)fpID; if (ilcdDb.AddIlcdEntity(flow, uuid)) { isSaved = true; flowId = flow.FlowID; } } if (flowId != 0) // successful import or existing object { // add flow properties that don't already exist var ffp = CreateFFPList(ilcdDb, flowId); ilcdDb.AddEntities<FlowFlowProperty>(ffp); // add classification data if it is not already present var cs = CreateClassificationList(ilcdDb, uuid); ilcdDb.AddEntities<Classification>(cs); Program.Logger.InfoFormat("Added {0} FlowFlowProperty entries and {1} Classification entries", ffp.Count(), cs.Count()); } return isSaved; }
private int GetCategoryIdForIntermediate(DbContextWrapper ilcdDb, XElement c) { string externalClassId = c.Attribute("classId").Value; return ilcdDb.GetDbSet<Category>().AsQueryable().Where(a => a.ExternalClassID == externalClassId) .Select(a => a.CategoryID).FirstOrDefault(); }
/// <summary> /// Create a process flow entity from an Process exchange. /// </summary> /// <param name="ilcdDb">Database context wrapper object</param> /// <param name="el">Process exchange element</param> /// <param name="processID">Process parent entity ID</param> private ProcessFlow CreateProcessFlow(DbContextWrapper ilcdDb, XElement el, int processID) { ProcessFlow pf = null; string varName = (string)el.Element(ElementName("referenceToVariable")); string type; if (el.Element(_CommonNamespace + "other") == null ) { type = "none"; } else { type=(string)el.Element(_CommonNamespace + "other").Element(_GabiNamespace + "GaBi").Attribute("IOType"); } double magnitude = (double)el.Element(ElementName("meanAmount")); double result = (double)el.Element(ElementName("resultingAmount")); double stdev = 0; if ( el.Element("relativeStandardDeviation95In") != null) { stdev = (double)el.Elements(ElementName("relativeStandardDeviation95In")).FirstOrDefault(); } string uuid = el.Element(ElementName("referenceToFlowDataSet")).Attribute("refObjectId").Value; int flowID; if (ilcdDb.FindRefIlcdEntityID<Flow>(uuid, out flowID)) { string direction = (string)el.Element(ElementName(("exchangeDirection"))); int? dirID = ilcdDb.LookupEntityID<Direction>(direction); if (dirID == null) { Program.Logger.WarnFormat("Unable to find ID for exchangeDirection = {0}", direction); } string location = (string)el.Element(ElementName(("location"))); pf = new ProcessFlow { DirectionID = (int)dirID, FlowID = flowID, Geography = location, Magnitude = magnitude, ProcessID = processID, Result = result, STDev = stdev, Type = type, VarName = varName }; } return pf; }
/// <summary> /// Entry point of console app. /// </summary> static int Main(string[] args) { int exitCode = 0; bool loadedFiles = false; try { StartLogging(); if (ParseArguments(args)) { if (_DeleteFlag) { Database.SetInitializer<EntityDataModel>(new DropCreateDatabaseInitializer()); } else if (_InitFlag) { Database.SetInitializer<EntityDataModel>(new CreateDatabaseInitializer()); } else if (_UpgradeFlag) { var configuration = new Configuration(); var migrator = new DbMigrator(configuration); migrator.Update(); Logger.InfoFormat("Upgraded database."); Database.SetInitializer<EntityDataModel>(null); } else { Database.SetInitializer<EntityDataModel>(null); } DbContextWrapper dbContext = new DbContextWrapper(); if (!String.IsNullOrEmpty(_IlcdDirName)) { if (Directory.Exists(_IlcdDirName)) { IlcdImporter ilcdImporter = new IlcdImporter(); ilcdImporter.LoadAll(_IlcdDirName, _IlcdSourceName, dbContext, File.Exists(_PrivateFileName)); Logger.InfoFormat("Loaded ILCD archive from {0}.", _IlcdDirName); loadedFiles = true; } else { Logger.ErrorFormat("ILCD folder, {0}, does not exist.", _IlcdDirName); exitCode = 1; } } if (_CsvFlag) { if (Directory.Exists(_DataRoot)) { CsvImporter.LoadAll(_DataRoot, dbContext); Logger.InfoFormat("Loaded CSV folders under {0}.", _DataRoot); loadedFiles = true; } else { Logger.ErrorFormat("Data Root folder, {0}, does not exist.", _DataRoot); exitCode = 1; } } if (loadedFiles) { Program.Logger.InfoFormat("Update LCIA Flow reference..."); dbContext.UpdateLciaFlowID(); } } } catch (Exception e) { Logger.FatalFormat("Unexpected Exception: {0}", e.Message); for (var ie = e.InnerException; ie != null; ie = ie.InnerException) { Program.Logger.FatalFormat("Inner exception: {0}", ie.Message); } Console.Write(e.ToString()); exitCode = 1; } finally { StopLogging(); } return exitCode; }
/// <summary> /// Create a list of FlowFlowProperty entities from elements under flowProperties. /// This will only add entries that do not exist, but will not update entries that do exist. /// </summary> /// <param name="ilcdDb">Database context wrapper object</param> /// <param name="flow">Flow parent entity</param> private List<FlowFlowProperty> CreateFFPList(DbContextWrapper ilcdDb, int flowId) { var ffpExist = ilcdDb.GetDbSet<FlowFlowProperty>().AsQueryable().Where(k => k.FlowID == flowId).Select(k => k.FlowPropertyID).ToList(); return LoadedDocument.Root.Descendants(ElementName("flowProperties")).Elements(ElementName("flowProperty")) .Select(fp => new FlowFlowProperty { FlowID = flowId, FlowPropertyID = GetFlowPropertyID(ilcdDb, fp), MeanValue = (double)fp.Element(ElementName("meanValue")), StDev = (double?)fp.Element(ElementName("relativeStandardDeviation95In")) }).Where(fp => !ffpExist.Contains(fp.FlowPropertyID)).ToList(); }
/// <summary> /// Create an LCIA entity from an LCIAMethod characterization factor. /// </summary> /// <param name="ilcdDb">Database context wrapper object</param> /// <param name="el">LCIAMethod characterization factor element</param> /// <param name="lciaMethodID">LCIAMethod parent entity ID</param> private LCIA CreateLCIA(DbContextWrapper ilcdDb, XElement el, int lciaMethodID, string lciaMethodUUID) { LCIA lcia = null; XElement refEl = el.Element(ElementName("referenceToFlowDataSet")); string uuid = refEl.Attribute("refObjectId").Value; double meanValue = (double)el.Element(ElementName(("meanValue"))); string direction = (string)el.Element(ElementName(("exchangeDirection"))); string location = (string)el.Element(ElementName(("location"))); string name = (string)refEl.Element(_CommonNamespace + "shortDescription"); // Most of the referenced flows will not be found, so don't bother searching for them now. // The program will update LCIA flow references before exiting. //Flow flow = ilcdDb.GetIlcdEntity<Flow>(uuid); //int? id = null; //if (flow == null) { // Program.Logger.WarnFormat("Unable to find flow matching LCIA refObjectId = {0}", uuid); //} //else { // id = flow.FlowID; //} int? dirID = ilcdDb.LookupEntityID<Direction>(direction); if (dirID == null) { Program.Logger.ErrorFormat("Invalid LCIA exchangeDirection : {0}, refObjectId = {1}. LCIA Method UUID = {2}. Skipping record.", direction, uuid, lciaMethodUUID); } else { int reqDirID = Convert.ToInt32(dirID); lcia = new LCIA { //FlowID = id, FlowUUID = uuid, FlowName = name, DirectionID = reqDirID, Factor = meanValue, Geography = location, LCIAMethodID = lciaMethodID }; } return lcia; }
public MethodCallConfiguration(DbContextWrapper wrapper) { Wrapper = wrapper; }
private int GetCategoryIdForElementary(DbContextWrapper ilcdDb, XElement c) { string name = c.Value; return ilcdDb.GetDbSet<Category>().AsQueryable().Where(a => a.Name == name && a.CategorySystem.Name == "ILCDEflow") .Select(a => a.CategoryID).FirstOrDefault(); }
public PropertyChainConfiguration(DbContextWrapper wrapper) { _wrapper = wrapper; }
/// <summary> /// Extract UUID from referenceToFlowPropertyDataSet and transform it to entity ID (FlowPropertyID). /// This depends on the referenced flow property having been previously imported. /// </summary> /// <param name="ilcdDb">Database context wrapper object</param> /// <param name="fpElement">Element containing referenceToFlowPropertyDataSet</param> /// <returns>Entity ID, if the UUID was extracted and a loaded entity ID was found, otherwise null</returns> private int GetFlowPropertyID(DbContextWrapper ilcdDb, XElement fpElement) { string fpUUID = fpElement.Element(ElementName("referenceToFlowPropertyDataSet")).Attribute("refObjectId").Value; int fpID; if (ilcdDb.FindRefIlcdEntityID<FlowProperty>( fpUUID, out fpID)) { return fpID; } else { throw new ArgumentNullException("fpID","FlowProperty UUID not found."); } }
public static void ContextFilter( this DbContextWrapper wrapper, EntityTypeBuilder <ExtensionContextFilter> builder) => builder.HasQueryFilter(e => e.IsEnabled == wrapper.Context.IndirectionFlag.Enabled);
/// <summary> /// Import data from loaded flowproperty file to new FlowProperty entity /// </summary> /// <param name="ilcdDb">Database context wrapper object</param> /// <returns>true iff data was imported</returns> private bool SaveFlowProperty(DbContextWrapper ilcdDb) { bool isSaved = false; string ugUUID; string uuid = GetCommonUUID(); if (!ilcdDb.IlcdEntityAlreadyExists<FlowProperty>(uuid)) { FlowProperty flowProperty = new FlowProperty(); SaveIlcdEntity(ilcdDb, flowProperty, DataTypeEnum.FlowProperty); flowProperty.Name = GetCommonName(); ugUUID = GetElementAttributeValue(ElementName("referenceToReferenceUnitGroup"), "refObjectId"); if (ugUUID == null) { Program.Logger.WarnFormat("Unable to find referenceToReferenceUnitGroup in flow property {0}", flowProperty.ILCDEntity.UUID); } else { int ugID; if (ilcdDb.FindRefIlcdEntityID<UnitGroup>(ugUUID, out ugID)) { flowProperty.UnitGroupID = ugID; } } isSaved = ilcdDb.AddIlcdEntity(flowProperty, uuid); } return isSaved; }
public static void ConfigureFilter(EntityTypeBuilder <RemoteMethodParamsFilter> builder, DbContextWrapper wrapper) => builder.HasQueryFilter(e => e.Tenant == wrapper.Context.IndirectionFlag.GetId());
private bool SaveLciaMethod(DbContextWrapper ilcdDb) { bool isSaved = false; string lookupName; string refUUID; string uuid = GetCommonUUID(); if (!ilcdDb.IlcdEntityAlreadyExists<LCIAMethod>(uuid)) { LCIAMethod lciaMethod = new LCIAMethod(); SaveIlcdEntity(ilcdDb, lciaMethod, DataTypeEnum.LCIAMethod); lciaMethod.Name = GetCommonName(); lciaMethod.Methodology = GetElementValue(ElementName("methodology")); lookupName = GetElementValue(ElementName("impactCategory")); if (lookupName != null) { lciaMethod.ImpactCategoryID = (int)ilcdDb.LookupEntityID<ImpactCategory>(lookupName); } lciaMethod.ImpactIndicator = GetElementValue(ElementName("impactIndicator")); lookupName = GetElementValue(ElementName("typeOfDataSet")); if (lookupName != null) { lciaMethod.IndicatorTypeID = ilcdDb.LookupEntityID<IndicatorType>(lookupName); } lciaMethod.ReferenceYear = GetElementValue(ElementName("referenceYear")); lciaMethod.Duration = GetElementValue(ElementName("duration")); lciaMethod.ImpactLocation = GetElementValue(ElementName("impactLocation")); lciaMethod.Normalization = Convert.ToBoolean(GetElementValue(ElementName("normalisation"))); lciaMethod.Weighting = Convert.ToBoolean(GetElementValue(ElementName("weighting"))); lciaMethod.UseAdvice = GetElementValue(ElementName("useAdviceForDataSet")); refUUID = GetElementAttributeValue(ElementName("referenceQuantity"), "refObjectId"); Debug.Assert(refUUID != null); int refID; if (ilcdDb.FindRefIlcdEntityID<FlowProperty>(refUUID, out refID)) { lciaMethod.ReferenceFlowPropertyID = refID; } if (ilcdDb.AddIlcdEntity(lciaMethod, uuid)) { List<LCIA> lciaList = LoadedDocument.Root.Descendants(ElementName("characterisationFactors")).Elements(ElementName("factor")).Select(f => CreateLCIA(ilcdDb, f, lciaMethod.ID, uuid)).ToList(); ilcdDb.AddEntities<LCIA>(lciaList); isSaved = true; } } return isSaved; }
/// <summary> /// Import data from LoadedDocument to database. /// </summary> /// <param name="ilcdDb">Database context wrapper object</param> /// <returns>true iff data was imported</returns> public bool Save(DbContextWrapper ilcdDb) { bool isSaved = false; Debug.Assert(LoadedDocument != null, "LoadedDocument must be set before calling Save."); string nsString = LoadedDocument.Root.Name.Namespace.ToString(); switch (nsString) { case "http://lca.jrc.it/ILCD/UnitGroup": isSaved = SaveUnitGroup(ilcdDb); break; case "http://lca.jrc.it/ILCD/FlowProperty": isSaved = SaveFlowProperty(ilcdDb); break; case "http://lca.jrc.it/ILCD/Flow": isSaved = SaveFlow(ilcdDb); break; case "http://lca.jrc.it/ILCD/LCIAMethod": isSaved = SaveLciaMethod(ilcdDb); break; case "http://lca.jrc.it/ILCD/Process": isSaved = SaveProcess(ilcdDb); break; case "http://lca.jrc.it/ILCD/Source": isSaved = SaveStub(ilcdDb, DataTypeEnum.Source); break; case "http://lca.jrc.it/ILCD/Contact": isSaved = SaveStub(ilcdDb, DataTypeEnum.Contact); break; } return isSaved; }
private bool SaveStub(DbContextWrapper ilcdDb, DataTypeEnum dtEnum) { bool isSaved = false; string uuid = GetCommonUUID(); if (ilcdDb.GetIlcdEntity(GetCommonUUID()) == null) { ILCDEntity stub = SaveIlcdStub(ilcdDb, dtEnum); isSaved = ilcdDb.AddEntity<ILCDEntity>(stub); } return isSaved; }
private List<Classification> CreateClassificationList(DbContextWrapper ilcdDb, string uuid) { int ilcdEntityId = ilcdDb.GetIlcdEntity(uuid).ILCDEntityID; var catExist = ilcdDb.GetDbSet<Classification>().AsQueryable().Where(c => c.ILCDEntityID == ilcdEntityId) .Select(c => c.CategoryID).ToList(); var classInfo = LoadedDocument.Root.Descendants(ElementName("classificationInformation")).FirstOrDefault(); var c1 = new List<Classification>(); c1.AddRange(classInfo.Element(_CommonNamespace + "elementaryFlowCategorization").Elements(_CommonNamespace + "category") .Select(c => new Classification { ILCDEntityID = ilcdEntityId, CategoryID = GetCategoryIdForElementary(ilcdDb, c) }).Where(c => c.CategoryID !=0).ToList()); if (c1.Count() == 0) { try { c1.AddRange(classInfo.Element(_CommonNamespace + "classification").Elements(_CommonNamespace + "class") .Select(c => new Classification { ILCDEntityID = ilcdEntityId, CategoryID = GetCategoryIdForIntermediate(ilcdDb, c) }).Where(c => c.CategoryID != 0).ToList()); } catch (Exception e) { Program.Logger.ErrorFormat("Something went wrong"); } } return c1.Where(c => !catExist.Contains(c.CategoryID)).ToList(); }
/// <summary> /// 初始化一个<see cref="RepositoryBase{TEntity,TKey}"/>类型的实例 /// </summary> /// <param name="unitOfWork">工作单元</param> protected RepositoryBase(IUnitOfWork unitOfWork) { _wrapper = new DbContextWrapper <TEntity, TKey>(unitOfWork); UnitOfWork = _wrapper.UnitOfWork; Set = _wrapper.Set; }
public DbEntityEntryWrapper(DbContextWrapper contextWrapper, DbEntityEntry <TEntity> entityEntry) : base(contextWrapper, entityEntry) { }