• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# DbContext类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中DbContext的典型用法代码示例。如果您正苦于以下问题:C# DbContext类的具体用法?C# DbContext怎么用?C# DbContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



DbContext类属于命名空间,在下文中一共展示了DbContext类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: AddActiveDirectoryUser

        protected static void AddActiveDirectoryUser(Guid userId, string name, string accountName, bool isDisabled = false,
            IEnumerable<KeyValuePair<string, string>> customProperties = null)
        {
            using (DbContext writeDbContext = new DbContext())
            {
                User user = new User
                {
                    Id = userId,
                    Name = name,
                    IsDisabled = isDisabled,
                };

                Account account = new Account
                {
                    UserId = user.Id,
                    Name = accountName,
                    Type = AccountType.ActiveDirectory
                };

                user.Accounts.Add(account);

                if (customProperties != null)
                {
                    user.CustomProperties.AddRange(customProperties.Select(c => new CustomProperty { Id = Guid.NewGuid(), Name = c.Key, Value = c.Value }));
                }

                writeDbContext.Users.Add(user);
                writeDbContext.SaveChanges();
            }
        }
开发者ID:affecto,项目名称:dotnet-IdentityManagement,代码行数:30,代码来源:DbTests.cs


示例2: ConcreteDatabase

 public ConcreteDatabase(
     DbContext context,
     IRelationalDataStoreCreator dataStoreCreator,
     ILoggerFactory loggerFactory)
     : base(context, dataStoreCreator, loggerFactory)
 {
 }
开发者ID:thegido,项目名称:EntityFramework,代码行数:7,代码来源:RelationalDatabaseExtensionsTest.cs


示例3: ShouldQueryFirms

        public void ShouldQueryFirms()
        {
            var model = CreateModel();

            using (var connection = CreateConnection())
            using (var context = new DbContext(connection, model.Compile(), false))
            {
                var firm = context.Set<Firm>()
                    .Include(x => x.Balances)
                    .Include(x => x.Categories)
                    .Include(x => x.CategoryGroup)
                    .Include(x => x.Client)
                    .Include(x => x.Client.CategoryGroup)
                    .Include(x => x.Client.Contacts)
                    .Include(x => x.Territories)
                    .OrderBy(x => x.Id)
                    .FirstOrDefault();

                Assert.That(firm, Is.Not.Null);
                Assert.That(firm.Name, Is.Not.Null.And.EqualTo("Firm 1"));
                Assert.That(firm.Balances, Is.Not.Null.And.Count.EqualTo(2));
                Assert.That(firm.Categories, Is.Not.Empty.And.Count.EqualTo(1));
                Assert.That(firm.CategoryGroup, Is.Not.Null);
                Assert.That(firm.Client, Is.Not.Null.And.Property("Name").EqualTo("Client 1"));
                Assert.That(firm.Client.CategoryGroup, Is.Not.Null);
                Assert.That(firm.Client.Contacts, Is.Not.Null.And.Count.EqualTo(3));
                Assert.That(firm.Territories, Is.Not.Empty.And.Count.EqualTo(2));
            }
        }
开发者ID:gitter-badger,项目名称:nuclear-river,代码行数:29,代码来源:EdmxBuilderModelTests.cs


示例4: Store

 public void Store(DbContext dbContext)
 {
     if (HttpContext.Current.Items.Contains(DataContextKey))
         HttpContext.Current.Items[DataContextKey] = dbContext;
     else
         HttpContext.Current.Items.Add(DataContextKey, dbContext);
 }
开发者ID:chitraju-chaithanya,项目名称:inse6260,代码行数:7,代码来源:HttpDataContextStorageContainer.cs


示例5: TryGetModelHash

        /// <summary>
        ///     Attempts to get the model hash calculated by Code First for the given context.
        ///     This method will return null if the context is not being used in Code First mode.
        /// </summary>
        /// <param name = "context">The context.</param>
        /// <returns>The hash string.</returns>
        public static string TryGetModelHash(DbContext context)
        {
            //Contract.Requires(context != null);

            var compiledModel = context.InternalContext.CodeFirstModel;
            return compiledModel == null ? null : new ModelHashCalculator().Calculate(compiledModel);
        }
开发者ID:jimmy00784,项目名称:entityframework,代码行数:13,代码来源:EdmMetadata.cs


示例6: CheckRegionAllowed

        public static void CheckRegionAllowed(IPrincipal principal,DbContext db, string regionID)
        {
            String userID = ((KawalDesaIdentity)principal.Identity).User.Id;
            if (userID == null)
                throw new ApplicationException("region is not allowed for thee");

            var region = db.Set<Region>()
                .AsNoTracking()
                .Include(r => r.Parent)
                .Include(r => r.Parent.Parent)
                .Include(r => r.Parent.Parent.Parent)
                .Include(r => r.Parent.Parent.Parent.Parent)
                .First(r => r.Id == regionID);

            var regionIDs = new List<string>();
            var current = region;
            while(current != null)
            {
                regionIDs.Add(current.Id);
                current = current.Parent;
            }

            var allowed = db.Set<UserScope>()
                .Any(s => s.fkUserId == userID && regionIDs.Contains(s.fkRegionId));
            if (!allowed)
                throw new ApplicationException("region is not allowed for thee");
        }
开发者ID:ekospinach,项目名称:kawaldesa,代码行数:27,代码来源:KawalDesaController.cs


示例7: EntityEntryGraphIterator

 public EntityEntryGraphIterator(
     [NotNull] DbContext context,
     [NotNull] IStateManager stateManager)
 {
     _context = context;
     _stateManager = stateManager;
 }
开发者ID:thegido,项目名称:EntityFramework,代码行数:7,代码来源:EntityEntryGraphIterator.cs


示例8: DbContextWrapper

        public DbContextWrapper(DbContext context)
        {
            Context = context;

            objectContext = ((IObjectContextAdapter) context).ObjectContext;
            objectContext.ObjectMaterialized += ObjectMaterializedHandler;
        }
开发者ID:popcatalin81,项目名称:DataAccess,代码行数:7,代码来源:DbContextWrapper.cs


示例9: CheckValue

        public void CheckValue(DbContext ctx, object actual)
        {
            var propertyType = Accessor.MemberType;

            var objectContext = ((IObjectContextAdapter)ctx).ObjectContext;
            var entitySet = objectContext.GetEntitySet(propertyType);
            var keyMembers = entitySet.ElementType.KeyMembers;

            ctx.Entry(actual).Reference(Accessor.Name).Load();

            var actualEntity = Accessor.GetValue(actual);
            if (actualEntity == null)
            {
                throw new AssertionException(ExpectedEntity.Dump(), "NULL");
            }
            foreach (var keyMember in keyMembers)
            {
                var accessor = new PropertyAccessor(propertyType.GetProperty(keyMember.Name));

                var actualKeyValue = accessor.GetValue(actualEntity);
                var expectedKeyValue = accessor.GetValue(ExpectedEntity);

                if (!expectedKeyValue.Equals(actualKeyValue))
                {
                    throw new AssertionException(ExpectedEntity.Dump(), actualEntity.Dump());
                }
            }
        }
开发者ID:kmcginnes,项目名称:EFSpecs,代码行数:28,代码来源:Reference.cs


示例10: FindSets

 protected virtual void FindSets(ModelBuilder modelBuilder, DbContext context)
 {
     foreach (var setInfo in SetFinder.FindSets(context))
     {
         modelBuilder.Entity(setInfo.EntityType);
     }
 }
开发者ID:aishaloshik,项目名称:EntityFramework,代码行数:7,代码来源:ModelSource.cs


示例11: Registrar

        public void Registrar(DbContext dbContext)
        {
            RegistrarModulo();
            RegistrarOperaciones();

            dbContext.Set<Formulario>().Add(_moduloFormulario);
        }
开发者ID:CamiCasus,项目名称:FiguraManager,代码行数:7,代码来源:ModuloBase.cs


示例12: EntityFrameworkExternalDataSource

 public EntityFrameworkExternalDataSource(DbContext dbContext)
 {
     _dbContext = dbContext;
     SetOptionsForDbContext(_dbContext);
     _efManager = new EFManager(dbContext);
     _efManager.ReloadDbEntries();
 }
开发者ID:GigaSpaces-ProfessionalServices,项目名称:xapnet-templates,代码行数:7,代码来源:EntityFrameworkExternalDataSource.cs


示例13: UserService

 public UserService(DbContext context, IRepository<User> users, IRepository<Message, int> messages)
 {
     this.users = users;
     this.messages = messages;
     this.userManager = new UserManager<User>(new UserStore<User>(context));
     this.roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
 }
开发者ID:atanas-georgiev,项目名称:ASP.NET-MVC-Final-Project,代码行数:7,代码来源:UserService.cs


示例14: GuardClause_all

		public void GuardClause_all()
		{
			Assert.Throws<ArgumentNullException>(() =>
			{
				var value = new DbContext(null, null);
			});
		}
开发者ID:gongdo,项目名称:orientdb-http-dnx,代码行数:7,代码来源:DbContextTests.cs


示例15: CurrentContext

 /// <copydocfrom cref="IDbContextProvider.CurrentContext" />
 public DbContext CurrentContext()
 {
     lock (syncLock)
     {
         return context ?? (context = func());
     }
 }
开发者ID:kevinwiegand,项目名称:EnergyTrading-Core,代码行数:8,代码来源:DbContextProvider.cs


示例16: ExecuteResources

 private static void ExecuteResources(DbContext context, IEnumerable<string> resources)
 {
     foreach (var resource in resources)
     {
         SqlBatchExecutor.ExecuteResourceStreamFromExecutingAssembly(context, resource);
     }
 }
开发者ID:MookieFumi,项目名称:ExposureCoverage,代码行数:7,代码来源:Program.cs


示例17: DbDependencyResolver

 public DbDependencyResolver(DbContext context)
 {
     this.context = context;
     this.usersRepository = new DbUsersRepository(context);
     this.newsArticlesRepository = new DbRepository<NewsArticle>(context);
     this.commentsRepository = new DbRepository<Comment>(context);
 }
开发者ID:vladislav-karamfilov,项目名称:TelerikAcademy,代码行数:7,代码来源:DbDependencyResolver.cs


示例18: AddTestData

        protected static void AddTestData(DbContext context)
        {
            var address1 = new Address { Street = "3 Dragons Way", City = "Meereen" };
            var address2 = new Address { Street = "42 Castle Black", City = "The Wall" };
            var address3 = new Address { Street = "House of Black and White", City = "Braavos" };

            context.Set<Person>().AddRange(
                new Person { Name = "Daenerys Targaryen", Address = address1 },
                new Person { Name = "John Snow", Address = address2 },
                new Person { Name = "Arya Stark", Address = address3 },
                new Person { Name = "Harry Strickland" });

            context.Set<Address>().AddRange(address1, address2, address3);

            var address21 = new Address2 { Id = "1", Street = "3 Dragons Way", City = "Meereen" };
            var address22 = new Address2 { Id = "2", Street = "42 Castle Black", City = "The Wall" };
            var address23 = new Address2 { Id = "3", Street = "House of Black and White", City = "Braavos" };

            context.Set<Person2>().AddRange(
                new Person2 { Name = "Daenerys Targaryen", Address = address21 },
                new Person2 { Name = "John Snow", Address = address22 },
                new Person2 { Name = "Arya Stark", Address = address23 });

            context.Set<Address2>().AddRange(address21, address22, address23);

            context.SaveChanges();
        }
开发者ID:RickyLin,项目名称:EntityFramework,代码行数:27,代码来源:OneToOneQueryFixtureBase.cs


示例19: AddUserWithCustomProperties

        public void AddUserWithCustomProperties()
        {
            Guid userId = Guid.NewGuid();
            const string userName = "user";

            const string emailName = "email";
            const string emailValue = "[email protected]";
            const string addressName = "address";
            const string addressValue = "street 123";

            var customProperties = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>(emailName,  emailValue),
                new KeyValuePair<string, string>(addressName, addressValue)
            };

            sut.AddUser(userId, userName, customProperties);
            sut.SaveChanges();

            using (DbContext readContext = new DbContext())
            {
                User user = readContext.Users.Include(u => u.CustomProperties).Single();

                Assert.AreEqual(userId, user.Id);
                Assert.AreEqual(userName, user.Name);

                Assert.AreEqual(2, user.CustomProperties.Count);
                Assert.IsNotNull(user.CustomProperties.SingleOrDefault(c => c.Name == emailName && c.Value == emailValue));
                Assert.IsNotNull(user.CustomProperties.SingleOrDefault(c => c.Name == addressName && c.Value == addressValue));
            }
        }
开发者ID:affecto,项目名称:dotnet-IdentityManagement,代码行数:31,代码来源:AddUserTests.cs


示例20: AppendDescriptionUsingContext

        private static void AppendDescriptionUsingContext(DbContext context, StringBuilder builder, EntityType type, ActionType aType, object entity)
        {
            string additionalInfo = string.Empty;
            string identity = string.Empty;
            var enrty = context.Entry(entity);

            var prop =
                enrty.Entity.GetType()
                    .GetProperties()
                    .FirstOrDefault(c => c.GetCustomAttributes(typeof(KeyAttribute), true).FirstOrDefault() != null);
            var name = enrty.Entity.GetType().GetProperties().FirstOrDefault(c => c.Name.Contains("Name"));

            identity = CreateIdentityString(entity, prop, identity, name);

            if (aType == ActionType.Updating)
            {
                additionalInfo = string.Format("Были изменены следующие поля: {0}",
                    string.Join(",", enrty.CurrentValues.PropertyNames));
            }

            if (aType != ActionType.Import || aType != ActionType.Export)
            {
                builder.Append(string.Format("Сущность \"{0}\" {1} была {2}.{3}", type.GetEntityTypeName(), identity,
                    aType.GetActionTypeName(), additionalInfo));
            }
        }
开发者ID:Shkorodenok,项目名称:Articles,代码行数:26,代码来源:TransactionHelper.cs



注:本文中的DbContext类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# DbContextCustomerRepository类代码示例发布时间:2022-05-24
下一篇:
C# DbConnection类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap