/// <summary> /// Finds the associated org units. /// </summary> /// <param name="objectContext">The object context.</param> /// <param name="dto">The DTO.</param> /// <returns>An enumerable of the associated Org Unit IDs</returns> public static IEnumerable<int> FindAssociatedOrgUnits(ObjectContext objectContext, AssociatedOrgUnitsDto dto) { List<int> relatedUnits = new List<int>(); var orgUnitAssociationPublished = objectContext.CreateObjectSet<OrgUnitAssociationPublished>(); var orgUnitPublished = objectContext.CreateObjectSet<OrgUnitPublished>(); if (dto.OrganizationalUnitId.HasValue) { var orgUnitIdAsList = new List<int>() { dto.OrganizationalUnitId.Value }; if (dto.DescendantOption != DescendantOption.NoDescendants) { var newUnits = GetDescendants(orgUnitIdAsList, dto.DescendantOption, orgUnitAssociationPublished, orgUnitPublished); AddUnitsToList(ref relatedUnits, newUnits); } if (dto.LinkedOption != LinkedOption.NoLinkedUnits) { var newUnits = GetLinkedUnits(orgUnitIdAsList, dto.LinkedOption, orgUnitAssociationPublished, orgUnitPublished); AddUnitsToList(ref relatedUnits, newUnits); } //add the current org unit AddUnitsToList(ref relatedUnits, new List<int> { dto.OrganizationalUnitId.Value }); } return relatedUnits.ToArray(); }
public List<User> GetAllUsers() { using (ObjectContext context = new ObjectContext(_connectionString)) { return context.CreateObjectSet<User>().ToList(); } }
public Article GetArticle() { using (ObjectContext context = new ObjectContext(_connectionString)) { return context.CreateObjectSet<Article>().FirstOrDefault(x => x.Id == 1); } }
private static Event BuildKeywordsWithInternalGenerator(int eventId, ObjectContext objectContext) { // Fetch event entity var eventEntity = objectContext.CreateObjectSet<Event>().Include("EventTopicAssociations.EventTopic").Single(e => e.Id == eventId); // Sanitize custom keywords and build generated keywords var generatedKeywords = new StringBuilder(); var delimiter = Utils.Common.Keywords.KeywordUtils.ResolveKeywordDelimiter(eventEntity.CustomKeywords); eventEntity.CustomKeywords = Utils.Common.Keywords.KeywordUtils.SanitizeKeywords(eventEntity.CustomKeywords, _excludedWords, delimiter); // Append custom keywords if (eventEntity.CustomKeywords != null) generatedKeywords.Append(eventEntity.CustomKeywords); // Append event topics if (eventEntity.EventTopicAssociations.Count() > 0) generatedKeywords.Append(delimiter + string.Join(",", eventEntity.EventTopicAssociations.Select(e => e.EventTopic.Name).ToArray())); // Sanitize and persist keywords var sanitizedKeywords = Utils.Common.Keywords.KeywordUtils.SanitizeKeywords(generatedKeywords.ToString(), _excludedWords); eventEntity.Keywords = sanitizedKeywords; return eventEntity; }
private static Service BuildKeywordsWithInternalGenerator(int serviceId, ObjectContext objectContext) { // Fetch service entity var service = objectContext.CreateObjectSet<Service>().Single(s => s.Id == serviceId); // Sanitize custom keywords and build generated keywords var generatedKeywords = new StringBuilder(); var delimiter = Utils.Common.Keywords.KeywordUtils.ResolveKeywordDelimiter(service.CustomKeywords); service.CustomKeywords = Utils.Common.Keywords.KeywordUtils.SanitizeKeywords(service.CustomKeywords, _excludedWords, delimiter); // Append custom keywords if (service.CustomKeywords != null) generatedKeywords.Append(service.CustomKeywords); // Append service name if (service.Name != null) generatedKeywords.Append(delimiter + service.Name); // Sanitize and persist keywords var sanitizedKeywords = Utils.Common.Keywords.KeywordUtils.SanitizeKeywords(generatedKeywords.ToString(), _excludedWords); service.Keywords = sanitizedKeywords; return service; }
/// <summary> /// Validates the user integration entity. /// </summary> /// <param name="userIntegration">The user integration.</param> /// <param name="context">The context.</param> /// <returns></returns> public static StatusMessage ValidateUserIntegrationEntity(UserIntegrationDto userIntegration, ObjectContext context) { const int maximumExternalIdLength = 50; const int maximumExternalSystemLength = 500; if (userIntegration == null) { return StatusMessage.MissingData; } if (userIntegration.UserId == 0) { return StatusMessage.InvalidData; } if (string.IsNullOrEmpty(userIntegration.ExternalId) || userIntegration.ExternalId.Length > maximumExternalIdLength) { return StatusMessage.InvalidData; } if (string.IsNullOrEmpty(userIntegration.ExternalSystem) || userIntegration.ExternalSystem.Length > maximumExternalSystemLength) { return StatusMessage.InvalidData; } if (context.CreateObjectSet<DAL.UserIntegration>().Count(u => u.UserId == userIntegration.UserId && u.ExternalSystem == userIntegration.ExternalSystem && u.Id != userIntegration.Id) > 0) { return StatusMessage.DuplicateData; } return StatusMessage.Success; }
public Picture GetPicture(int id) { using (ObjectContext context = new ObjectContext(this._connectionString)) { return context.CreateObjectSet<Picture>().Single(x=>x.Id == id); } }
public Picture GetPicture(string src) { using (ObjectContext context = new ObjectContext(this._connectionString)) { return context.CreateObjectSet<Picture>().Single(x=>x.Src == src); } }
public PersonPageInfo GetPersonPageInfo() { using (ObjectContext context = new ObjectContext(_connectionString)) { return context.CreateObjectSet<PersonPageInfo>().FirstOrDefault(x => x.Id == 1); } }
private static OrgUnit BuildKeywordsWithInternalGenerator(int orgUnitId, ObjectContext objectContext) { // Fetch orgUnit entity with related data var orgUnitSet = objectContext.CreateObjectSet<OrgUnit>() .Include("OrgUnitServices.Service") .Include("OrgUnitTypeAssociations.OrgUnitType"); var orgUnit = orgUnitSet.Single(o => o.Id == orgUnitId); // Sanitize custom keywords and build generated keywords var generatedKeywords = new StringBuilder(); var delimiter = Utils.Common.Keywords.KeywordUtils.ResolveKeywordDelimiter(orgUnit.CustomKeywords); orgUnit.CustomKeywords = Utils.Common.Keywords.KeywordUtils.SanitizeKeywords(orgUnit.CustomKeywords, _excludedWords, delimiter); // Append custom keywords if (orgUnit.CustomKeywords != null) generatedKeywords.Append(orgUnit.CustomKeywords); // Append org unit type names generatedKeywords.Append(delimiter + String.Join(delimiter, orgUnit.OrgUnitTypeAssociations.Select(t => t.OrgUnitType.Name))); // Append service names generatedKeywords.Append(delimiter + String.Join(delimiter, orgUnit.OrgUnitServices.Select(s => s.Service.Name))); // Sanitize and persist keywords var sanitizedKeywords = Utils.Common.Keywords.KeywordUtils.SanitizeKeywords(generatedKeywords.ToString(), _excludedWords); orgUnit.Keywords = sanitizedKeywords; return orgUnit; }
public void AddNewUser(string firstname, string surname, string email, string description, string username, string password, byte[] imagebyte, string imgtype) { using (ObjectContext context = new ObjectContext(_connectionString)) { var users = context.CreateObjectSet<User>(); int maxId = users.Any() ? users.Max(x => x.Id) : 1; int pictureId = _pictureRepository.AddPicture(imagebyte, imgtype, string.Empty); User newUser = new User() { Id = +maxId, Firstname = firstname, Surname = surname, Email = email, DateRegister = DateTime.Now, Description = description, Username = username, Password = password, isEnable = true, isAdmin = false, PictureId = pictureId }; users.AddObject(newUser); context.SaveChanges(); }; }
public List<Article> GetPublished() { using (ObjectContext context = new ObjectContext(_connectionString)) { return context.CreateObjectSet<Article>() .Where(u => u.Published == true).ToList(); } }
public bool CheckUniqueTitle(string title) { using (ObjectContext context = new ObjectContext(_connectionString)) { bool isExists = context.CreateObjectSet<Article>().Any(u => u.Title == title); return !isExists; }; }
public Comment[] GetArticleComments(int articleId) { using (ObjectContext context = new ObjectContext(_connectionString)) { return context.CreateObjectSet<Comment>() .Where(u => u.ArticleId == articleId).ToArray(); } }
public bool CheckUnicueUsername(string username) { using (ObjectContext context = new ObjectContext(_connectionString)) { bool isExists = context.CreateObjectSet<User>().Any(x => x.Username == username); return isExists ? false : true; } }
public void DoWork() { var context = new ObjectContext(_connectionString); var firstMember = context.CreateObjectSet<Member>() .OrderByDescending(m => m.firstName) .First(); firstMember.licenseExpiration = firstMember.licenseExpiration.AddDays(1); var lastMember = context.CreateObjectSet<Member>() .OrderBy(m => m.licenseExpiration) .First(); lastMember.firstName = "Jacob"; context.SaveChanges(); }
protected static int? ResolveOrgUnitId(ObjectContext context, string internalId, string externalId) { int? orgUnitId = null; if (!string.IsNullOrEmpty(externalId)) { var mapping = context.CreateObjectSet<DataImportEntityIdMap>().FirstOrDefault(m => m.EntityName == "OrgUnit" && m.ExternalId == externalId); if (mapping == null) throw new BusinessException("Unknown OrgUnitExternalId: " + externalId); orgUnitId = mapping.InternalId; } else { orgUnitId = GetNullableInt(internalId); } if (orgUnitId.HasValue && !context.CreateObjectSet<OrgUnit>().Any(ou => ou.Id == orgUnitId.Value)) throw new BusinessException("Invalid OrgUnitID:" + orgUnitId.Value.ToString(CultureInfo.InvariantCulture)); return orgUnitId; }
public void SetArticleContent(string content) { using (ObjectContext context = new ObjectContext(_connectionString)) { Article article = context.CreateObjectSet<Article>().Single(x => x.Id == 1); article.Content = content; context.SaveChanges(); } }
public void ChangePublishingStatus(Article article) { using (ObjectContext context = new ObjectContext(_connectionString)) { var oldArticle = context.CreateObjectSet<Article>().Single(x => x.Id ==article.Id); oldArticle.Published = article.Published; context.SaveChanges(); } }
public void EntityConnectionFactory_CreateTransientEntityConnection_InitializesDataSchema() { EntityConnection connection = EntityConnectionFactory.CreateTransient(NorthwindObjectContext.DefaultConnectionString); using (ObjectContext context = new ObjectContext(connection)) { Assert.IsTrue(context.DatabaseExists()); Assert.AreEqual(0, context.CreateObjectSet<Product>().Count(), "Zero rows in the fake table"); } }
private static void BuildKeywordsWithExternalGenerator(int serviceId, string oldCustomKeywords, ObjectContext objectContext) { // Fetch service entity var service = objectContext.CreateObjectSet<Service>().Single(s => s.Id == serviceId); // Get updated custom and generated keywords var keywordPair = BuildKeywordsForExternalGenerator(service.Keywords, oldCustomKeywords ?? service.CustomKeywords, service.CustomKeywords, _excludedWords); service.CustomKeywords = keywordPair.CustomKeywords; service.Keywords = keywordPair.GeneratedKeywords; }
private static void BuildKeywordsWithExternalGenerator(int ClinicalTrialId, string oldCustomKeywords, ObjectContext objectContext) { // Fetch ClinicalTrial entity var ClinicalTrial = objectContext.CreateObjectSet<ClinicalTrial>().Single(a => a.Id == ClinicalTrialId); // Get updated custom and generated keywords var keywordPair = BuildKeywordsForExternalGenerator(ClinicalTrial.Keywords, oldCustomKeywords ?? ClinicalTrial.CustomKeywords, ClinicalTrial.CustomKeywords, _excludedWords); ClinicalTrial.CustomKeywords = keywordPair.CustomKeywords; ClinicalTrial.Keywords = keywordPair.GeneratedKeywords; }
private static void BuildKeywordsWithExternalGenerator(int eventId, string oldCustomKeywords, ObjectContext objectContext) { // Fetch event entity var eventEntity = objectContext.CreateObjectSet<Event>().Single(e => e.Id == eventId); // Get updated custom and generated keywords var keywordPair = BuildKeywordsForExternalGenerator(eventEntity.Keywords, oldCustomKeywords ?? eventEntity.CustomKeywords, eventEntity.CustomKeywords, _excludedWords); eventEntity.CustomKeywords = keywordPair.CustomKeywords; eventEntity.Keywords = keywordPair.GeneratedKeywords; }
public byte[] GetContentImage(int id) { byte[] data; using (ObjectContext context = new ObjectContext(_connectionString)) { User user = context.CreateObjectSet<User>().Single(x => x.Id == id); Picture picture = _pictureRepository.GetPicture(user.PictureId); data = picture.FileData; } return data; }
public void SetPersonPageInfo(string mainInfo, string diagnosis, string moneyInfo) { using (ObjectContext context = new ObjectContext(_connectionString)) { PersonPageInfo article = context.CreateObjectSet<PersonPageInfo>().Single(x => x.Id == 1); article.MainInfo = mainInfo; article.Diagnosis = diagnosis; article.MoneyInfo = moneyInfo; context.SaveChanges(); } }
private static void BuildKeywordsWithExternalGenerator(int orgUnitId, string oldCustomKeywords, ObjectContext objectContext) { // Fetch provider entity var orgUnit = objectContext.CreateObjectSet<OrgUnit>().Single(o => o.Id == orgUnitId); // Get updated custom and generated keywords var keywordPair = BuildKeywordsForExternalGenerator(orgUnit.Keywords, oldCustomKeywords ?? orgUnit.CustomKeywords, orgUnit.CustomKeywords, _excludedWords); orgUnit.CustomKeywords = keywordPair.CustomKeywords; orgUnit.Keywords = keywordPair.GeneratedKeywords; }
private static void BuildKeywordsWithExternalGenerator(int providerId, string oldCustomKeywords, ObjectContext objectContext) { // Fetch provider entity var provider = objectContext.CreateObjectSet<Provider>().Single(p => p.Id == providerId); // Build excluded keywords list var excludedKeywords = KeywordUtils.AddSanitizedKeywordsToArray(_globalExcludedKeywords, provider.ExcludedKeywords); // Get updated custom and generated keywords var keywordPair = BuildKeywordsForExternalGenerator(provider.Keywords, oldCustomKeywords ?? provider.CustomKeywords, provider.CustomKeywords, excludedKeywords); provider.CustomKeywords = keywordPair.CustomKeywords; provider.Keywords = keywordPair.GeneratedKeywords; }
public static IEnumerable<OrgUnitAssociationDto> AddOutsideOrgUnitType(ObjectContext objectContext, IEnumerable<OrgUnitAssociationDto> query) { var orgUnitTypeAssociations = objectContext.CreateObjectSet<OrgUnitTypeAssociation>().AsNoTracking(); var orgUnitTypes = objectContext.CreateObjectSet<OrgUnitType>().AsNoTracking(); var response = (from orgassoc in (from a in query join t in orgUnitTypeAssociations on a.SecondaryId equals t.OrgUnitId into at from ato in at.DefaultIfEmpty() select new { org = a, orgUnitTypeId = ato != null ? ato.OrgUnitTypeId : 0 }) join o in orgUnitTypes on orgassoc.orgUnitTypeId equals o.Id into oa from b in oa.DefaultIfEmpty() select new OrgUnitAssociationDto { Id = orgassoc.org.Id, PrimaryId = orgassoc.org.PrimaryId, PrimaryName = orgassoc.org.PrimaryName, PrimaryLinkedId = orgassoc.org.PrimaryLinkedId, SecondaryId = orgassoc.org.SecondaryId, SecondaryName = orgassoc.org.SecondaryName, SecondaryLinkedId = orgassoc.org.SecondaryLinkedId, SecondaryIsEnabled = orgassoc.org.SecondaryIsEnabled, SecondaryIsSite = orgassoc.org.SecondaryIsSite, SecondaryCustomUrl = orgassoc.org.SecondaryCustomUrl, IsEnabled = orgassoc.org.IsEnabled, HasAscendant = orgassoc.org.HasAscendant, HasDescendant = orgassoc.org.HasDescendant, HasUniqueApplicationSettings = orgassoc.org.HasUniqueApplicationSettings, IsOutsideOfOrganization = b == null || b.IsOutsideOfOrganization, IsParentSite = oa.Any(ty => ty.SiteIndicator && ty.Id == orgassoc.orgUnitTypeId) }).ToArray().OrderBy(x => x.SecondaryId).ThenBy(x => x.IsOutsideOfOrganization).GroupBy(x => x.SecondaryId).Select(g => g.FirstOrDefault()).ToArray(); return response; }
protected static void LookupCountryId(ObjectContext context, string name, OrgUnit orgUnit) { if (name.IsNullOrWhiteSpace()) return; var item = context.CreateObjectSet<Country>().SingleOrDefault(s => s.Name == name); if (item != null) { orgUnit.CountryId = item.Id; } else { throw new BusinessException(string.Format(CultureInfo.InvariantCulture, "Country with the name of {0} does not exists", name)); } }
/// <summary> /// Finds the CustomURL of the Org Unit or of it's closest parent. /// </summary> /// <param name="context">The context.</param> /// <param name="orgUnit">The org unit.</param> /// <returns></returns> public static string FindOrgUnitUrl(ObjectContext context, OrgUnit orgUnit) { if (orgUnit.OrgUnitTypeAssociations.Any(t => t.OrgUnitType.SiteIndicator) && !string.IsNullOrEmpty(orgUnit.CustomUrl)) return orgUnit.CustomUrl; return context.CreateObjectSet<OrgUnitAssociationPublished>() .Where(o => o.Direction == "Reverse") .Where(o => o.PrimaryId == orgUnit.Id) .Where(o => o.OrgUnitSecondary.CustomUrl != null && o.OrgUnitSecondary.CustomUrl != string.Empty) .Where(o => o.OrgUnitSecondary.OrgUnitTypeAssociations.Any(t => t.OrgUnitType.SiteIndicator)) .Where(o => o.OrgUnitSecondary.IsEnabled) .OrderBy(o => o.Distance) .Select(o => o.OrgUnitSecondary.CustomUrl) .FirstOrDefault(); }
public IObjectSet <T> CreateObjectSet <T>() where T : class { return(_context.CreateObjectSet <T>()); }
public Repository() { _context = new EmploymentProfilerDB(); _objectSet = _context.CreateObjectSet <T>(); }
public IObjectSet <TEntity> CreateObjectSet <TEntity>() where TEntity : class { return(context.CreateObjectSet <TEntity>()); }
/// <summary> /// Initializes a new instance of the <see cref="Repository<T>"/> class. /// </summary> /// <param name="context">The context.</param> public Repository(ObjectContext context) { this.objectSet = context.CreateObjectSet <T>(); }
/// <summary> /// 所有数据的查询列表 /// </summary> /// <returns></returns> public IQueryable <TEntity> FindAll() { return(_objectContext.CreateObjectSet <TEntity>().AsQueryable()); }
private static string GetEntitySetName <T>(ObjectContext context) where T : class { var objectSet = context.CreateObjectSet <T>(); return($"{objectSet.EntitySet.EntityContainer.Name}.{objectSet.EntitySet.Name}"); }
public WorkTrekRepository(string connectionString) { ObjectContext = new ObjectContext(connectionString); ObjectSet = ObjectContext.CreateObjectSet <T>(); }
private static ObjectSet <T> CreateObjectSet <T>(ObjectContext context, T entity) where T : class { return(context.CreateObjectSet <T>()); }
public Repository(DbContext context) { _context = (context as IObjectContextAdapter).ObjectContext; _objectSet = _context.CreateObjectSet <TEntity>(); //_context.ContextOptions.LazyLoadingEnabled = true; Default! }
public SQLRepository(ObjectContext context) { _objectSet = context.CreateObjectSet <T>(); _context = context; }
internal void LoadRecordsToDatabase() { List <String> recordsToAdd = readAllRecordsAndSymbol(); ObjectContext context = new ObjectContext(connectionString); ObjectSet <Company> companies = context.CreateObjectSet <Company>(); // Console.WriteLine("nr of records before persist : " + company.Count()); ObjectSet <Record> records = context.CreateObjectSet <Record>(); Console.WriteLine("nr of records before persist : " + records.Count()); for (int i = 0; i < recordsToAdd.Count; i += 7) { Record r = new Record(); String companySymbol = recordsToAdd[i]; Company companyForRecord = companies.Single(c => c.Symbol == companySymbol); r.CompanySymbol = companySymbol; r.High = float.Parse(recordsToAdd[i + 1]); r.Low = float.Parse(recordsToAdd[i + 2]); r.Close = float.Parse(recordsToAdd[i + 3]); // r.Volume = int.Parse(recordsToAdd[i + 4]); String volume = recordsToAdd[i + 4].Replace(",", ""); r.Volume = int.Parse(volume); r.ChangeOne = float.Parse(recordsToAdd[i + 5]); r.ChangeTwo = float.Parse(recordsToAdd[i + 6]); //DateTime today = new DateTime(); // var sqlFormattedDate = today.Date.ToString("yyyy-MM-dd HH:mm:ss"); r.DateOfRecord = DateTime.Today; //c.Symbol = companiesToAdd[i]; // c.Name = companiesToAdd[i + 1]; // company.AddObject(c); //r.Id = (System.Guid)1; // r.Id = 3; companyForRecord.Records.Add(r); records.AddObject(r); } //Console.WriteLine(company.Count()); //Company c = new Company(); // c.Symbol = "CYST"; // c.Name = "WAR"; // company.AddObject(c); try { context.SaveChanges(); } catch (Exception e) { Console.WriteLine("--catched : " + e.Message); } ObjectSet <Record> record2 = context.CreateObjectSet <Record>(); Console.WriteLine("after insering number of records is : " + record2.Count()); context.Dispose(); }
public IEnumerable <Customer> Get() { IEnumerable <Customer> customers = default(IEnumerable <Customer>); // ************************************************************************************************************************* // The ADO.NET way // ************************************************************************************************************************* using (IReadRepository <Customer> customerRepository = new CustomerRepository(nameof(ExamCodeFirstContext))) { customers = customerRepository.Get(); } // ************************************************************************************************************************* // The Entity Framework way // ************************************************************************************************************************* using (IRepository <Customer> customerRepository = new EfRepository <Customer>(new ExamCodeFirstContext())) { customers = customerRepository.Get(); } // ************************************************************************************************************************* // The Model First Way // ************************************************************************************************************************* using (IRepository <Core.Model_First.Customer> customerRepository = new EfRepository <Core.Model_First.Customer>(new Core.Model_First.ExamModelFirstContext())) { IEnumerable <Core.Model_First.Customer> customersFromModelFirst = customerRepository.Get(); } // ************************************************************************************************************************* // The DI way // ************************************************************************************************************************* customers = this.CustomerRepository.Get(); // ************************************************************************************************************************* // The good old way of the ObjectContext // ************************************************************************************************************************* if (this.CustomerRepository is EfRepository <Customer> ) { // Use explicit conversion to get the DbContext from the repository without exposing the DbContext property as public ExamCodeFirstContext ctx = (ExamCodeFirstContext)(EfRepository <Customer>) this.CustomerRepository; IQueryable <Customer> customersDeferred = ctx.Customers.Where(x => x.Id > 1); customersDeferred.Load(); customersDeferred.Where(x => x.FirstName == "Donald"); IQueryable <Customer> customersDeferred2 = ctx.Customers.Where(x => x.Id > 1); customersDeferred2.Where(x => x.FirstName == "Donald"); // Use the adapter to get to the old ObjectContext type IObjectContextAdapter adapter = (IObjectContextAdapter)ctx; ObjectContext objectContext = adapter.ObjectContext; // Create same query as the others with the ObjectContext directly ObjectQuery <Customer> customersQuery = objectContext.CreateObjectSet <Customer>(); // Get the trace string of the objcect query string query = customersQuery.ToTraceString(); customers = customersQuery; } return(customers.ToList()); }
public static string GetEntitySetNameOf <TEntity>(this ObjectContext context) where TEntity : class { return(context.CreateObjectSet <TEntity>().EntitySet.Name); }
/// <summary> /// Returns a Full Qualified EntitySet Name /// </summary> /// <typeparam name="T"></typeparam> /// <param name="pDbContext"></param> /// <returns></returns> public static string GetQualifiedEntitySetName <T>(this DbContext pDbContext) where T : DBEntityBase { ObjectContext context = (pDbContext as IObjectContextAdapter).ObjectContext; return(string.Format("{0}.{1}", context.DefaultContainerName, context.CreateObjectSet <T>().EntitySet.Name)); }
public Repository(DbContext context, bool lazyLoading) { _context = (context as IObjectContextAdapter).ObjectContext; _objectSet = _context.CreateObjectSet <TEntity>(); _context.ContextOptions.LazyLoadingEnabled = lazyLoading; }
/// <summary> /// The get entity properties. /// </summary> /// <param name="context"> /// The context. /// </param> /// <typeparam name="TEntity"> /// The entity type. /// </typeparam> /// <returns> /// The <see cref="System.Collections.Generic.List{String}" />. /// </returns> public static List <string> GetEntityProperties <TEntity>(this ObjectContext context) where TEntity : class { var objectSet = context.CreateObjectSet <TEntity>(); return(objectSet.EntitySet.ElementType.Properties.Select(x => x.Name).ToList()); }
/// <summary> /// Inicializa uma nova instância do repositório /// </summary> /// <param name="contexto">O Objeto contexto do Entity Framework </param> /// <param name="chave"> Identifica o contexto criado </param> public RepositorioGenerico() { _context = new SaceEntities(global::Dados.Properties.Settings.Default.SaceEntities); _objectSet = _context.CreateObjectSet <T>(); }
/// <summary> /// Inicializa uma nova instância do repositório /// </summary> /// <param name="contexto">O Objeto contexto do Entity Framework </param> /// <param name="chave"> Identifica o contexto criado </param> public RepositorioGenerico(ObjectContext context) { _context = context; _objectSet = _context.CreateObjectSet <T>(); }
public GenericRepository(ObjectContext context) { _context = context; _objectSet = _context.CreateObjectSet <TEntity>(); }
protected Repository(ObjectContext context) { _objectSet = context.CreateObjectSet <T>(); }
/// <summary> /// Returns an <see cref="IQueryable{T}"/>. /// </summary> /// <typeparam name="T">Generic Argument of the returned <see cref="IQueryable{T}"/>.</typeparam> /// <returns>Returns an <see cref="IQueryable{T}"/>.</returns> public IQueryable <T> Get <T>() where T : class { return(objectContext.CreateObjectSet <T>()); }
public override void Add <T>(T entity) { context .CreateObjectSet <T>() .AddObject(entity); }
private int InternalUpdate <TEntity>(ObjectContext objectContext, EntityMap entityMap, ObjectQuery <TEntity> query, Expression <Func <TEntity, TEntity> > updateExpression, bool async = false) where TEntity : class #endif { DbConnection updateConnection = null; DbTransaction updateTransaction = null; DbCommand updateCommand = null; bool ownConnection = false; bool ownTransaction = false; try { // get store connection and transaction var store = GetStore(objectContext); updateConnection = store.Item1; updateTransaction = store.Item2; if (updateConnection.State != ConnectionState.Open) { updateConnection.Open(); ownConnection = true; } // use existing transaction or create new if (updateTransaction == null) { updateTransaction = updateConnection.BeginTransaction(); ownTransaction = true; } updateCommand = updateConnection.CreateCommand(); updateCommand.Transaction = updateTransaction; if (objectContext.CommandTimeout.HasValue) { updateCommand.CommandTimeout = objectContext.CommandTimeout.Value; } var innerSelect = GetSelectSql(query, entityMap, updateCommand); var sqlBuilder = new StringBuilder(innerSelect.Length * 2); sqlBuilder.Append("UPDATE "); sqlBuilder.Append(entityMap.TableName); sqlBuilder.AppendLine(" SET "); var memberInitExpression = updateExpression.Body as MemberInitExpression; if (memberInitExpression == null) { throw new ArgumentException("The update expression must be of type MemberInitExpression.", "updateExpression"); } int nameCount = 0; bool wroteSet = false; foreach (MemberBinding binding in memberInitExpression.Bindings) { if (wroteSet) { sqlBuilder.AppendLine(", "); } string propertyName = binding.Member.Name; string columnName = entityMap.PropertyMaps .Where(p => p.PropertyName == propertyName) .Select(p => p.ColumnName) .FirstOrDefault(); var memberAssignment = binding as MemberAssignment; if (memberAssignment == null) { throw new ArgumentException("The update expression MemberBinding must only by type MemberAssignment.", "updateExpression"); } Expression memberExpression = memberAssignment.Expression; ParameterExpression parameterExpression = null; memberExpression.Visit((ParameterExpression p) => { if (p.Type == entityMap.EntityType) { parameterExpression = p; } return(p); }); if (parameterExpression == null) { object value; if (memberExpression.NodeType == ExpressionType.Constant) { var constantExpression = memberExpression as ConstantExpression; if (constantExpression == null) { throw new ArgumentException( "The MemberAssignment expression is not a ConstantExpression.", "updateExpression"); } value = constantExpression.Value; } else { LambdaExpression lambda = Expression.Lambda(memberExpression, null); value = lambda.Compile().DynamicInvoke(); } if (value != null) { string parameterName = "p__update__" + nameCount++; var parameter = updateCommand.CreateParameter(); parameter.ParameterName = parameterName; parameter.Value = value; updateCommand.Parameters.Add(parameter); sqlBuilder.AppendFormat("[{0}] = @{1}", columnName, parameterName); } else { sqlBuilder.AppendFormat("[{0}] = NULL", columnName); } } else { // create clean objectset to build query from var objectSet = objectContext.CreateObjectSet <TEntity>(); Type[] typeArguments = new[] { entityMap.EntityType, memberExpression.Type }; ConstantExpression constantExpression = Expression.Constant(objectSet); LambdaExpression lambdaExpression = Expression.Lambda(memberExpression, parameterExpression); MethodCallExpression selectExpression = Expression.Call( typeof(Queryable), "Select", typeArguments, constantExpression, lambdaExpression); // create query from expression var selectQuery = objectSet.CreateQuery(selectExpression, entityMap.EntityType); string sql = selectQuery.ToTraceString(); // parse select part of sql to use as update string regex = @"SELECT\s*\r\n\s*(?<ColumnValue>.+)?\s*AS\s*(?<ColumnAlias>\[\w+\])\r\n\s*FROM\s*(?<TableName>\[\w+\]\.\[\w+\]|\[\w+\])\s*AS\s*(?<TableAlias>\[\w+\])"; Match match = Regex.Match(sql, regex); if (!match.Success) { throw new ArgumentException("The MemberAssignment expression could not be processed.", "updateExpression"); } string value = match.Groups["ColumnValue"].Value; string alias = match.Groups["TableAlias"].Value; value = value.Replace(alias + ".", ""); foreach (ObjectParameter objectParameter in selectQuery.Parameters) { string parameterName = "p__update__" + nameCount++; var parameter = updateCommand.CreateParameter(); parameter.ParameterName = parameterName; parameter.Value = objectParameter.Value ?? DBNull.Value; updateCommand.Parameters.Add(parameter); value = value.Replace(objectParameter.Name, parameterName); } sqlBuilder.AppendFormat("[{0}] = {1}", columnName, value); } wroteSet = true; } sqlBuilder.AppendLine(" "); sqlBuilder.AppendFormat("FROM {0} AS j0 INNER JOIN (", entityMap.TableName); sqlBuilder.AppendLine(); sqlBuilder.AppendLine(innerSelect); sqlBuilder.Append(") AS j1 ON ("); bool wroteKey = false; foreach (var keyMap in entityMap.KeyMaps) { if (wroteKey) { sqlBuilder.Append(" AND "); } sqlBuilder.AppendFormat("j0.[{0}] = j1.[{0}]", keyMap.ColumnName); wroteKey = true; } sqlBuilder.Append(")"); updateCommand.CommandText = sqlBuilder.ToString(); #if NET45 int result = async ? await updateCommand.ExecuteNonQueryAsync() : updateCommand.ExecuteNonQuery(); #else int result = updateCommand.ExecuteNonQuery(); #endif // only commit if created transaction if (ownTransaction) { updateTransaction.Commit(); } return(result); } finally { if (updateCommand != null) { updateCommand.Dispose(); } if (updateTransaction != null && ownTransaction) { updateTransaction.Dispose(); } if (updateConnection != null && ownConnection) { updateConnection.Close(); } } }
public GenericRepository() { _context = ((IObjectContextAdapter) new tourdulichEntities()).ObjectContext; _objectSet = _context.CreateObjectSet <T>(); }
public MembershipRepository() { _context = new ASPNETDBEntities(); _userObjectSet = _context.CreateObjectSet <aspnet_Users>(); _roleObjectSet = _context.CreateObjectSet <aspnet_Roles>(); }
public Repository(ObjectContext context) { _context = context; _objectSet = context.CreateObjectSet <T>(); }
public static string GetTableName <T>(this ObjectContext context) where T : class { var m = Regex.Match(context.CreateObjectSet <T>().ToTraceString(), "FROM (?<table>.*) AS"); return(m != null ? m.Groups["table"].Value : null); }
public ObjectSet <T> CreateObjectSet <T>() where T : class, IEntity { return(_objectContext.CreateObjectSet <T>()); }
private int InternalUpdate <TEntity>(ObjectContext objectContext, EntityMap entityMap, ObjectQuery <TEntity> query, Expression <Func <TEntity, TEntity> > updateExpression, bool async = false) where TEntity : class #endif { using (var db = QueryHelper.GetDb(objectContext)) { var innerSelect = QueryHelper.GetSelectKeySql(query, entityMap, db.Command, this); var sqlBuilder = new StringBuilder(innerSelect.Length * 2); sqlBuilder.Append("UPDATE "); sqlBuilder.Append(entityMap.TableName); sqlBuilder.AppendFormat(" AS j0 INNER JOIN (", entityMap.TableName); sqlBuilder.AppendLine(); sqlBuilder.AppendLine(innerSelect); sqlBuilder.Append(") AS j1 ON ("); bool wroteKey = false; foreach (var keyMap in entityMap.KeyMaps) { if (wroteKey) { sqlBuilder.Append(" AND "); } sqlBuilder.AppendFormat("j0.{0} = j1.{0}", keyMap.ColumnName); wroteKey = true; } sqlBuilder.Append(")"); sqlBuilder.AppendLine(" "); sqlBuilder.AppendLine(" SET "); var memberInitExpression = updateExpression.Body as MemberInitExpression; if (memberInitExpression == null) { throw new ArgumentException("The update expression must be of type MemberInitExpression.", "updateExpression"); } int nameCount = 0; bool wroteSet = false; foreach (MemberBinding binding in memberInitExpression.Bindings) { if (wroteSet) { sqlBuilder.AppendLine(", "); } string propertyName = binding.Member.Name; string columnName = entityMap.PropertyMaps .Where(p => p.PropertyName == propertyName) .Select(p => p.ColumnName) .FirstOrDefault(); var memberAssignment = binding as MemberAssignment; if (memberAssignment == null) { throw new ArgumentException("The update expression MemberBinding must only by type MemberAssignment.", "updateExpression"); } Expression memberExpression = memberAssignment.Expression; ParameterExpression parameterExpression = null; memberExpression.Visit((ParameterExpression p) => { if (p.Type == entityMap.EntityType) { parameterExpression = p; } return(p); }); if (parameterExpression == null) { object value; if (memberExpression.NodeType == ExpressionType.Constant) { var constantExpression = memberExpression as ConstantExpression; if (constantExpression == null) { throw new ArgumentException( "The MemberAssignment expression is not a ConstantExpression.", "updateExpression"); } value = constantExpression.Value; } else { LambdaExpression lambda = Expression.Lambda(memberExpression, null); value = lambda.Compile().DynamicInvoke(); } if (value != null) { string parameterName = "p__update__" + nameCount++; var parameter = db.Command.CreateParameter(); parameter.ParameterName = parameterName; parameter.Value = value; db.Command.Parameters.Add(parameter); sqlBuilder.AppendFormat("{0} = @{1}", columnName, parameterName); } else { sqlBuilder.AppendFormat("{0} = NULL", columnName); } } else { // create clean objectset to build query from var objectSet = objectContext.CreateObjectSet <TEntity>(); Type[] typeArguments = new[] { entityMap.EntityType, memberExpression.Type }; ConstantExpression constantExpression = Expression.Constant(objectSet); LambdaExpression lambdaExpression = Expression.Lambda(memberExpression, parameterExpression); MethodCallExpression selectExpression = Expression.Call( typeof(Queryable), "Select", typeArguments, constantExpression, lambdaExpression); // create query from expression var selectQuery = objectSet.CreateQuery(selectExpression, entityMap.EntityType); string sql = selectQuery.ToTraceString(); // parse select part of sql to use as update string regex = @"SELECT\s*\r\n(?<ColumnValue>.+)?\s*AS\s*(?<ColumnAlias>\w+)\r\nFROM\s*(?<TableName>\w+\.\w+|\w+)\s*AS\s*(?<TableAlias>\w+)"; Match match = Regex.Match(sql, regex); if (!match.Success) { throw new ArgumentException("The MemberAssignment expression could not be processed.", "updateExpression"); } string value = match.Groups["ColumnValue"].Value; string alias = match.Groups["TableAlias"].Value; value = value.Replace(alias + ".", "j0."); foreach (ObjectParameter objectParameter in selectQuery.Parameters) { string parameterName = "p__update__" + nameCount++; var parameter = db.Command.CreateParameter(); parameter.ParameterName = parameterName; parameter.Value = objectParameter.Value; db.Command.Parameters.Add(parameter); value = value.Replace(objectParameter.Name, parameterName); } sqlBuilder.AppendFormat("{0} = {1}", columnName, value); } wroteSet = true; } db.Command.CommandText = sqlBuilder.ToString(); #if NET45 int result = async ? await db.Command.ExecuteNonQueryAsync().ConfigureAwait(false) : db.Command.ExecuteNonQuery(); #else int result = db.Command.ExecuteNonQuery(); #endif // only commit if created transaction if (db.OwnTransaction) { db.Transaction.Commit(); } return(result); } }
public ObjectSetProxy(ObjectContext context) { Entities = context.CreateObjectSet <BaseEntityType>(); }