当前位置: 首页>>代码示例>>C#>>正文


C# DataContext.Add方法代码示例

本文整理汇总了C#中DataContext.Add方法的典型用法代码示例。如果您正苦于以下问题:C# DataContext.Add方法的具体用法?C# DataContext.Add怎么用?C# DataContext.Add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在DataContext的用法示例。


在下文中一共展示了DataContext.Add方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ShouldLogAtDebugLevel

        public void ShouldLogAtDebugLevel()
        {
            //arrange 
            var logger = new ConsoleOutLogger("Testing", LogLevel.Trace, true, true, true, string.Empty);
            var target = new DataContext(Settings.Default.Connection, new DriversEducationMappings(), logger);

            //act
            var firstDriver = new Driver("Devlin", "Liles");
            target.Add(firstDriver);
            target.Add(new Driver("Tim", "Rayburn"));
            target.Add(new Driver("Jay", "Smith"));
            target.Add(new Driver("Brian", "Sullivan"));
            target.Add(new Driver("Cori", "Drew"));

            target.Commit();

            target.Reload(firstDriver);

            foreach (var driver in target.AsQueryable<Driver>())
            {
                target.Remove(driver);
            }


            target.Commit();

            target.ExecuteSqlQuery<Driver>("Select * from Drivers Where LastName = @lastName",
                new DbParameter[] {new SqlParameter("lastName", "Liles")});

            //assert
            //Assert.Inconclusive("We fail here to get the output from console nice and easy");
        }
开发者ID:joswalt,项目名称:Highway.Data,代码行数:32,代码来源:ContextLoggingTests.cs

示例2: GetDataContext

        protected virtual IDataContext GetDataContext(View view, Context context, IAttributeSet attrs)
        {
            var dataContext = new DataContext();
            var strings = ReadStringAttributeValue(context, attrs, Resource.Styleable.Binding, BindingAttrIndex);
            if (strings != null && strings.Count != 0)
                dataContext.Add(ViewFactoryConstants.Bindings, strings);

            SetAttributeValue(view, context, attrs, Resource.Styleable.ItemsControl,
                Resource.Styleable.ItemsControl_ItemTemplate, AttachedMemberConstants.ItemTemplate, dataContext,
                ViewFactoryConstants.ItemTemplateId);

            SetAttributeValue(view, context, attrs, Resource.Styleable.ItemsControl,
                Resource.Styleable.ItemsControl_DropDownItemTemplate, AttachedMembers.AdapterView.DropDownItemTemplate,
                dataContext,
                ViewFactoryConstants.DropDownItemTemplateId);

            SetAttributeValue(view, context, attrs, Resource.Styleable.Control,
                Resource.Styleable.Control_ContentTemplate, AttachedMemberConstants.ContentTemplate, dataContext,
                ViewFactoryConstants.ContentTemplateId);

            SetAttributeValue(view, context, attrs, Resource.Styleable.Menu,
                Resource.Styleable.Menu_MenuTemplate, AttachedMembers.Toolbar.MenuTemplate, dataContext,
                ViewFactoryConstants.MenuTemplateId);


            SetAttributeValue(view, context, attrs, Resource.Styleable.Menu,
                Resource.Styleable.Menu_PopupMenuTemplate, AttachedMembers.View.PopupMenuTemplate, dataContext,
                ViewFactoryConstants.PopupMenuTemplateId);

            strings = ReadStringAttributeValue(context, attrs, Resource.Styleable.Menu,
                new[] { Resource.Styleable.Menu_PopupMenuEvent });
            if (strings != null && strings.Count > 0)
            {
                string eventName = strings[0];
                dataContext.Add(ViewFactoryConstants.PopupMenuEvent, eventName);
                IBindingMemberInfo member = BindingServiceProvider
                    .MemberProvider
                    .GetBindingMember(view.GetType(), AttachedMembers.View.PopupMenuEvent, false, false);
                if (member != null)
                    member.SetValue(view, new object[] { eventName });
            }

            strings = ReadStringAttributeValue(context, attrs, Resource.Styleable.Menu,
                new[] { Resource.Styleable.Menu_PlacementTargetPath });
            if (strings != null && strings.Count > 0)
            {
                string path = strings[0];
                dataContext.Add(ViewFactoryConstants.PlacementTargetPath, path);
                IBindingMemberInfo member = BindingServiceProvider
                    .MemberProvider
                    .GetBindingMember(view.GetType(), AttachedMembers.View.PopupMenuPlacementTargetPath, false, false);
                if (member != null)
                    member.SetValue(view, new object[] { path });
            }

            return dataContext;
        }
开发者ID:MuffPotter,项目名称:MugenMvvmToolkit,代码行数:57,代码来源:ViewFactory.cs

示例3: CreateAndSaveDefaultCharity

        private static void CreateAndSaveDefaultCharity(Administrator defaultAdministrator, DataContext context)
        {
            var defaultCharity = new Charity
                {
                    SiteName = "My Charity",
                    Description = "This is a test charity"
                };

            defaultCharity.AddAdministrators(defaultAdministrator);

            context.Add(defaultCharity);
            context.SaveChanges();
        }
开发者ID:Gwayaboy,项目名称:MVCSolutionSample,代码行数:13,代码来源:PopulateDefaultCharityAndAdministrator.cs

示例4: SynchronizePageTypes

        public static void SynchronizePageTypes() {
            using (var context = new DataContext()) {
                var fetchStrategy = new FetchStrategy {MaxFetchDepth = 1};
                fetchStrategy.LoadWith<PageTypeEntity>(pt => pt.Properties);
                fetchStrategy.LoadWith<PropertyEntity>(p => p.PropertyType);
                context.FetchStrategy = fetchStrategy;

                var pageTypeEntities = context.PageTypes.ToList();
                var pageTypes = new List<PageType>();
                var typesWithAttribute = AttributeReader.GetTypesWithAttribute(typeof(PageTypeAttribute)).ToList();

                foreach (var type in typesWithAttribute) {
                    var attribute = AttributeReader.GetAttribute<PageTypeAttribute>(type);

                    var pageTypeEntity = pageTypeEntities.SingleOrDefault(pt => pt.Name == attribute.Name);

                    if (pageTypeEntity == null) {
                        pageTypeEntity = new PageTypeEntity();
                        pageTypeEntities.Add(pageTypeEntity);
                    }

                    pageTypeEntity.DefaultChildSortDirection = attribute.DefaultChildSortDirection;
                    pageTypeEntity.DefaultChildSortOrder = attribute.DefaultChildSortOrder;
                    pageTypeEntity.DisplayName = attribute.DisplayName;
                    pageTypeEntity.Name = attribute.Name;
                    pageTypeEntity.PageTemplate = attribute.PageTemplate;
                    pageTypeEntity.PageTypeDescription = attribute.PageTypeDescription;

                    if (pageTypeEntity.PageTypeId == 0) {
                        context.Add(pageTypeEntity);
                    }
                    context.SaveChanges();
                    
                    var pageType = Mapper.Map<PageTypeEntity, PageType>(pageTypeEntity);
                    pageType.Type = type;
                    pageType.AllowedTypes = attribute.AllowedTypes;
                    pageType.PreviewImage = attribute.PreviewImage;
                    pageType.Instance = (CmsPage)Activator.CreateInstance(type);

                    pageTypes.Add(pageType);

                    SynchronizeProperties(context, pageType, type, pageTypeEntity.Properties);
                }

                PageType.PageTypes = pageTypes;
            }
        }
开发者ID:KalikoCMS,项目名称:KalikoCMS.Core,代码行数:47,代码来源:Synchronizer.cs

示例5: Start

 /// <summary>
 ///     Starts the current bootstrapper.
 /// </summary>
 public virtual void Start()
 {
     InitializationContext = new DataContext(InitializationContext);
     if (!InitializationContext.Contains(NavigationConstants.IsDialog))
         InitializationContext.Add(NavigationConstants.IsDialog, false);
     Initialize();
     Type viewModelType = GetMainViewModelType();
     NavigationWindow rootWindow = null;
     var mappingProvider = IocContainer.Get<IViewMappingProvider>();
     IViewMappingItem mapping = mappingProvider.FindMappingForViewModel(viewModelType, InitializationContext.GetData(NavigationConstants.ViewName), true);
     if (typeof(Page).IsAssignableFrom(mapping.ViewType))
     {
         rootWindow = CreateNavigationWindow();
         var service = CreateNavigationService(rootWindow);
         IocContainer.BindToConstant(service);
     }
     var vm = CreateMainViewModel(viewModelType);
     vm.ShowAsync((model, result) =>
     {
         model.Dispose();
         if (ShutdownOnMainViewModelClose)
         {
             Application app = Application.Current;
             if (app != null)
             {
                 Action action = app.Shutdown;
                 app.Dispatcher.BeginInvoke(action);
             }
         }
     }, context: new DataContext(InitializationContext));
     if (rootWindow != null)
     {
         IWindowViewMediator mediator = new WindowViewMediator(rootWindow, vm, IocContainer.Get<IThreadManager>(),
             IocContainer.Get<IViewManager>(), IocContainer.Get<IWrapperManager>(),
             IocContainer.Get<IOperationCallbackManager>());
         mediator.UpdateView(new PlatformWrapperRegistrationModule.WindowViewWrapper(rootWindow), true, new DataContext(InitializationContext));
         rootWindow.Show();
     }
 }
开发者ID:MuffPotter,项目名称:MugenMvvmToolkit,代码行数:42,代码来源:WpfBootstrapperBase.cs

示例6: SynchronizeProperties

        private static void SynchronizeProperties(DataContext context, PageType pageType, Type type, IList<PropertyEntity> propertyEntities) {
            var propertyAttributeType = typeof(PropertyAttribute);
            var requiredAttributeType = typeof(RequiredAttribute);
            var properties = propertyEntities;
            var sortOrder = 0;

            foreach (var propertyInfo in type.GetProperties()) {
                var attributes = propertyInfo.GetCustomAttributes(true);

                var propertyAttribute = (PropertyAttribute)attributes.SingleOrDefault(propertyAttributeType.IsInstanceOfType);

                if (propertyAttribute != null) {
                    var propertyName = propertyInfo.Name;
                    var declaringType = propertyInfo.PropertyType;
                    var propertyTypeId = PropertyType.GetPropertyTypeId(declaringType);

                    if (!propertyAttribute.IsTypeValid(declaringType)) {
                        var notSupportedException = new NotSupportedException(string.Format("The property attribute of '{0}' on pagetype '{1}' ({2}) does not support the propertytype!", propertyName, pageType.Name, type.FullName));
                        Logger.Write(notSupportedException, Logger.Severity.Critical);
                        throw notSupportedException;
                    }

                    var required = attributes.Count(requiredAttributeType.IsInstanceOfType) > 0;

                    sortOrder++;

                    var property = properties.SingleOrDefault(p => p.Name == propertyName);

                    if (property == null) {
                        property = new PropertyEntity {Name = propertyName};
                        properties.Add(property);
                    }

                    property.PropertyTypeId = propertyTypeId;
                    property.PageTypeId = pageType.PageTypeId;
                    property.SortOrder = sortOrder;
                    property.Header = propertyAttribute.Header;
                    property.Required = required;

                    // If generic and standard attribute, store generic type as parameter. Required for list types like CollectionProperty.
                    if (declaringType.IsGenericType && propertyAttribute.GetType() == typeof(PropertyAttribute)) {
                        var subType = declaringType.GetGenericArguments()[0];
                        property.Parameters = subType.FullName + ", " + subType.Assembly.GetName().Name;
                    }
                    else {
                        property.Parameters = propertyAttribute.Parameters;
                    }

                    if (property.PropertyId == 0) {
                        context.Add(property);
                    }
                    
                    var propertyDefinition = Mapper.Map<PropertyEntity, PropertyDefinition>(property);
                    propertyDefinition.TabGroup = propertyAttribute.TabGroup;
                    pageType.Properties.Add(propertyDefinition);
                }
            }

            context.SaveChanges();
        }
开发者ID:KalikoCMS,项目名称:KalikoCMS.Core,代码行数:60,代码来源:Synchronizer.cs

示例7: SynchronizeSiteProperties

        public static void SynchronizeSiteProperties() {
            var typesWithAttribute = AttributeReader.GetTypesWithAttribute(typeof(SiteSettingsAttribute)).ToList();
            if (typesWithAttribute.Count > 1) {
                throw new Exception("More than one class implementing Site was found!");
            }
            if (!typesWithAttribute.Any()) {
                CmsSite.PropertyDefinitions = new List<PropertyDefinition>();
                return;
            }

            var type = typesWithAttribute.First();
            var siteSettingsAttribute = AttributeReader.GetAttribute<SiteSettingsAttribute>(type);
            CmsSite.AllowedTypes = siteSettingsAttribute.AllowedTypes;
            CmsSite.DefaultChildSortDirection = siteSettingsAttribute.DefaultChildSortDirection;
            CmsSite.DefaultChildSortOrder = siteSettingsAttribute.DefaultChildSortOrder;

            var definition = new List<PropertyDefinition>();
            var propertyAttributeType = typeof(PropertyAttribute);
            var requiredAttributeType = typeof(RequiredAttribute);
            var sortOrder = 0;

            using (var context = new DataContext()) {
                var properties = context.SitePropertyDefinitions.ToList();
                
                foreach (var propertyInfo in type.GetProperties()) {
                    var attributes = propertyInfo.GetCustomAttributes(true);

                    var propertyAttribute = (PropertyAttribute)attributes.SingleOrDefault(propertyAttributeType.IsInstanceOfType);

                    if (propertyAttribute != null) {
                        var propertyName = propertyInfo.Name;
                        var declaringType = propertyInfo.PropertyType;
                        var propertyTypeId = PropertyType.GetPropertyTypeId(declaringType);

                        if (!propertyAttribute.IsTypeValid(declaringType)) {
                            var notSupportedException = new NotSupportedException(string.Format("The property attribute of '{0}' on site settings ({1}) does not support the propertytype!", propertyName, type.FullName));
                            Logger.Write(notSupportedException, Logger.Severity.Critical);
                            throw notSupportedException;
                        }

                        var required = attributes.Count(requiredAttributeType.IsInstanceOfType) > 0;

                        sortOrder++;

                        var property = properties.SingleOrDefault(p => p.Name == propertyName);

                        if (property == null) {
                            property = new SitePropertyDefinitionEntity {Name = propertyName};
                            properties.Add(property);
                        }

                        property.PropertyTypeId = propertyTypeId;
                        property.SortOrder = sortOrder;
                        property.Header = propertyAttribute.Header;
                        property.Required = required;

                        // If generic and standard attribute, store generic type as parameter. Required for list types like CollectionProperty.
                        if (declaringType.IsGenericType && propertyAttribute.GetType() == typeof(PropertyAttribute)) {
                            var subType = declaringType.GetGenericArguments()[0];
                            property.Parameters = subType.FullName + ", " + subType.Assembly.GetName().Name;
                        }
                        else {
                            property.Parameters = propertyAttribute.Parameters;
                        }

                        if (property.PropertyId == 0) {
                            context.Add(property);
                        }

                        var propertyDefinition = Mapper.Map<SitePropertyDefinitionEntity, PropertyDefinition>(property);
                        propertyDefinition.TabGroup = propertyAttribute.TabGroup;
                        definition.Add(propertyDefinition);
                    }
                }

                context.SaveChanges();
            }

            CmsSite.PropertyDefinitions = definition;
        }
开发者ID:KalikoCMS,项目名称:KalikoCMS.Core,代码行数:80,代码来源:Synchronizer.cs

示例8: Parse

 public IList<IDataContext> Parse(object target, string bindingExpression, IList<object> sources, IDataContext context)
 {
     Should.NotBeNull(bindingExpression, nameof(bindingExpression));
     if (context == null)
         context = DataContext.Empty;
     KeyValuePair<KeyValuePair<string, int>, Action<IDataContext>[]>[] bindingValues;
     lock (_cache)
     {
         if (!_cache.TryGetValue(bindingExpression, out bindingValues))
         {
             try
             {
                 if (ReferenceEquals(context, DataContext.Empty))
                     context = _defaultContext;
                 context.AddOrUpdate(BindingBuilderConstants.Target, target);
                 _context = context;
                 _expression = Handle(bindingExpression, context);
                 _tokenizer = CreateTokenizer(Expression);
                 _memberVisitor.Context = context;
                 var value = ParseInternal()
                     .Select((pair, i) => new KeyValuePair<KeyValuePair<string, int>, Action<IDataContext>[]>(new KeyValuePair<string, int>(pair.Key, i), pair.Value))
                     .ToList();
                 value.Sort(MemberComparison);
                 bindingValues = value.ToArray();
                 if (!context.Contains(BindingBuilderConstants.NoCache))
                     _cache[bindingExpression] = bindingValues;
             }
             finally
             {
                 if (ReferenceEquals(_defaultContext, context))
                     _defaultContext.Clear();
                 _tokenizer = null;
                 _expression = null;
                 _context = null;
                 _memberVisitor.Context = null;
             }
         }
     }
     var result = new IDataContext[bindingValues.Length];
     if (sources != null && sources.Count > 0)
     {
         for (int i = 0; i < bindingValues.Length; i++)
         {
             var pair = bindingValues[i];
             var dataContext = new DataContext(context);
             dataContext.AddOrUpdate(BindingBuilderConstants.Target, target);
             if (pair.Key.Value < sources.Count)
             {
                 object src = sources[pair.Key.Value];
                 if (src != null)
                     dataContext.Add(BindingBuilderConstants.Source, src);
             }
             var actions = pair.Value;
             for (int j = 0; j < actions.Length; j++)
                 actions[j].Invoke(dataContext);
             result[i] = dataContext;
         }
     }
     else
     {
         for (int i = 0; i < bindingValues.Length; i++)
         {
             var actions = bindingValues[i].Value;
             var dataContext = new DataContext(context);
             dataContext.AddOrUpdate(BindingBuilderConstants.Target, target);
             for (int j = 0; j < actions.Length; j++)
                 actions[j].Invoke(dataContext);
             result[i] = dataContext;
         }
     }
     return result;
 }
开发者ID:dbeattie71,项目名称:MugenMvvmToolkit,代码行数:72,代码来源:BindingParser.cs

示例9: Start

 public virtual void Start()
 {
     Initialize();
     var app = MvvmApplication.Current;
     var ctx = new DataContext(app.Context);
     if (!ctx.Contains(NavigationConstants.IsDialog))
         ctx.Add(NavigationConstants.IsDialog, false);
     app.IocContainer
         .Get<IViewModelProvider>()
         .GetViewModel(app.GetStartViewModelType(), ctx)
         .ShowAsync((model, result) =>
         {
             model.Dispose();
             if (ShutdownOnMainViewModelClose)
                 Application.Exit();
         }, context: ctx);
     if (AutoRunApplication)
         Application.Run();
 }
开发者ID:sami1971,项目名称:MugenMvvmToolkit,代码行数:19,代码来源:WinFormsBootstrapperBase.cs

示例10: Start

 /// <summary>
 ///     Starts the current bootstrapper.
 /// </summary>
 public virtual void Start()
 {
     InitializationContext = new DataContext(InitializationContext);
     if (!InitializationContext.Contains(NavigationConstants.IsDialog))
         InitializationContext.Add(NavigationConstants.IsDialog, false);
     Initialize();
     var viewModelType = GetMainViewModelType();
     CreateMainViewModel(viewModelType)
         .ShowAsync((model, result) =>
         {
             model.Dispose();
             if (ShutdownOnMainViewModelClose)
                 Application.Exit();
         }, context: new DataContext(InitializationContext));
     if (AutoRunApplication)
         Application.Run();
 }
开发者ID:MuffPotter,项目名称:MugenMvvmToolkit,代码行数:20,代码来源:WinFormsBootstrapperBase.cs

示例11: KeepDatabaseUpToDate

        private static void KeepDatabaseUpToDate() {
            using (var context = new DataContext(true)) {
                // Keep schema up to date
                context.UpdateSchema();

                // TODO: Read languages from web.config (i.e. don't hard code 'English')
                // Ensure that at least one language is available
                if (!context.SiteLanguages.Any()) {
                    context.Add(new SiteLanguageEntity {
                        ShortName = "en",
                        LongName = "English"
                    });
                    context.SaveChanges();
                }
            }
        }
开发者ID:KalikoCMS,项目名称:KalikoCMS.Core,代码行数:16,代码来源:InitModule.cs


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