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

C# DataContext类代码示例

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

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



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

示例1: SetupAsync

        public async Task SetupAsync()
        {
            _evnt = new EventViewModel
            {
                Title = "Title event",
                Description = "Test event",
                Start = "11:00",
                End = "14:27",
                Date = "2016-02-01"
            };

            var userViewModel = new LoginViewModel
            {
                Email = "[email protected]",
                Password = "useruser",
                RememberMe = false
            };
            var context = new DataContext();
            var manager = new UserManager(new UserStore(context));
            var user = await manager.FindAsync(userViewModel.Email, userViewModel.Password);
            if (user == null)
            {
                await manager.CreateAsync(new User { Email = userViewModel.Email, UserName = userViewModel.Email }, userViewModel.Password);
            }
            _calendarController = new CalendarController(context);

            var mockCp = new Mock<IClaimsPrincipal>();
            if (user != null) mockCp.SetupGet(cp => cp.UserId).Returns(user.Id);
            _calendarController.CurrentUser = mockCp.Object;

            var mockAuthenticationManager = new Mock<IAuthenticationManager>();
            mockAuthenticationManager.Setup(am => am.SignOut());
            mockAuthenticationManager.Setup(am => am.SignIn());
            _calendarController.AuthenticationManager = mockAuthenticationManager.Object;
        }
开发者ID:kuite,项目名称:OrganizerMVC,代码行数:35,代码来源:CalendarTests.cs


示例2: Main

        static void Main(string[] args)
        {
            DataContext dc = new DataContext(@"Data Source=.\SQLEXPRESS;Initial Catalog=AdventureWorks;Integrated Security=True");

            dc.Log = Console.Out;

            //Table<Pessoa> pessoas = dc.GetTable<Pessoa>();

            var pessoas = from p in dc.GetTable<Pessoa>()
                          select p;

            //ObjectDumper.Write(pessoas);

            //Console.WriteLine();

            var nomes = from p in pessoas
                        select p.Nome;

            nomes = from p in nomes
                    where p.Equals("ABEL")
                    select p;

            ObjectDumper.Write(nomes);

            Console.ReadKey();
        }
开发者ID:50minutos,项目名称:MOC-10265,代码行数:26,代码来源:Program.cs


示例3: RepositoryBase

        /// <summary>
        /// Constructor initializes DataContext 
        /// plus adds additional configuration
        /// </summary>
        public RepositoryBase()
        {
            dc = new DataContext();

            dc.Configuration.LazyLoadingEnabled = false;
            dc.Configuration.ProxyCreationEnabled = false;
        }
开发者ID:ruslanjur,项目名称:Teacher-Student,代码行数:11,代码来源:RepositoryBase.cs


示例4: Login

        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                using (var db = new DataContext())
                {
                    ViewBag.LoginsList = db.Users.ToArray();
                }

                return View(model);
            }

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
            switch (result)
            {
                case SignInStatus.Success:
                    return RedirectToLocal(returnUrl);
                case SignInStatus.LockedOut:
                    return View("Lockout");
                case SignInStatus.RequiresVerification:
                    return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
                case SignInStatus.Failure:
                default:
                    ModelState.AddModelError("", "Invalid login attempt.");
                    return View(model);
            }
        }
开发者ID:panlukz,项目名称:logsol,代码行数:29,代码来源:AccountController.cs


示例5: AddOrUpdate

        private void AddOrUpdate(List<ExcelDeltaker> deltakere, DataContext context)
        {
            var alleLag = context.Lag.ToList();

            foreach (var excelDeltaker in deltakere)
            {
                var deltaker = context.Deltakere.SingleOrDefault(x => x.Kode == excelDeltaker.Kode);

                var lag = alleLag.SingleOrDefault(x => x.LagId == excelDeltaker.LagId);

                if (deltaker == null)
                {
                    context.Deltakere.Add(new Deltaker
                    {
                        DeltakerId = Guid.NewGuid().ToString(),
                        Navn = excelDeltaker.Navn,
                        Kode = excelDeltaker.Kode,
                        Lag = lag
                    });
                }
                else
                {
                    deltaker.Navn = excelDeltaker.Navn;
                    deltaker.Lag = lag;
                }
            }
        }
开发者ID:bouvet,项目名称:BBR2015,代码行数:27,代码来源:DeltakerImport.cs


示例6: CreateDBLinqDataContext

        //private static TextWriter dbLinqLogWriter = new StreamWriter(@"C:\Temp\sipsorcery\dblinq.log", true, Encoding.ASCII);

        public static DataContext CreateDBLinqDataContext(StorageTypes storageType, string connectionString) {
            DataContext dataContext = null;
            //DbProviderFactory factory = DbProviderFactories.GetFactory(providerName);
            //new MySql.Data.MySqlClient.MySqlClientFactory();
            //DbProviderFactory factory = Npgsql.NpgsqlFactory.Instance;
            
            switch (storageType) {
                case StorageTypes.DBLinqMySQL:
                    IDbConnection mySqlConn = new MySqlConnection(connectionString);
                    dataContext = new DataContext(mySqlConn, m_mappingSource, new DbLinq.MySql.MySqlVendor());
                    break;
                case StorageTypes.DBLinqPostgresql:
                    IDbConnection npgsqlConn = new NpgsqlConnection(connectionString);
                    dataContext = new DataContext(npgsqlConn, m_mappingSource, new DbLinq.PostgreSql.PgsqlVendor());
                    break;
                default:
                    throw new NotSupportedException("Database type " + storageType + " is not supported by CreateDBLinqDataContext.");
            }

            //dataContext.QueryCacheEnabled = true;
            //dataContext.Log = Console.Out;
            //dataContext.Log = dbLinqLogWriter;
            dataContext.ObjectTrackingEnabled = false;
            return dataContext;
        }
开发者ID:akalafrancis,项目名称:sipsorcery-mono,代码行数:27,代码来源:DBLinqContext.cs


示例7: EventCategorySingleViewModel

        public EventCategorySingleViewModel(string category, HttpServerUtilityBase server)
        {
            _server = server;

            category = formatCategoryString(category);

            //ImageList = getImageList();

            using (var context = new DataContext())
            {
                var tomorrow = DateTime.Now.Date;
                TheCategory = context.EventCategories.FirstOrDefault(x => x.CategoryName == category);

                EventRoll = context.Events.Where(x => x.MainCategory == category && x.IsActive == true && DateTime.Compare(x.EndDate.Value, tomorrow) >= 0).ToList();

                // Set a random picture on the eventRoll if none is currently set
                //foreach (var event in EventRoll)
                //{
                //	if (String.IsNullOrEmpty(event.ImageUrl))
                //	{
                //		event.ImageUrl = getRandomImage();
                //	}

                //}
            }
        }
开发者ID:marciocamello,项目名称:dirigo-edge,代码行数:26,代码来源:EventCategorySingleViewModel.cs


示例8: SiteTreeEditModel

        /// <summary>
        /// Creates a new site tree model for the given namespace.
        /// </summary>
        /// <param name="id">Namespace id</param>
        public SiteTreeEditModel(Guid namespaceId)
        {
            // Get the namespaces
            using (var db = new DataContext()) {
                var ns = db.Namespaces.OrderBy(n => n.Name).ToList() ;
                if (namespaceId != Guid.Empty)
                    Namespaces = new SelectList(ns, "Id", "Name", namespaceId) ;
                Namespaces = new SelectList(ns, "Id", "Name") ;
            }

            // Get the available region types
            RegionTypes = new List<dynamic>() ;
            ExtensionManager.Extensions.Where(e => e.ExtensionType == ExtensionType.Region).OrderBy(e => e.Name).Each((i, r) =>
                RegionTypes.Add(new { Name = r.Name, Type = r.Type.ToString() })) ;
            RegionTypes.Insert(0, new { Name = "", Type = "" }) ;

            // Initialize the new site
            Id = Guid.NewGuid() ;
            NamespaceId = namespaceId ;
            Template = new PageTemplate() {
                Id = Id,
                Name = Id.ToString(),
                IsSiteTemplate = true
            } ;
            Regions = Template.RegionTemplates ;
        }
开发者ID:springzh,项目名称:Piranha,代码行数:30,代码来源:SiteTreeEditModel.cs


示例9: TestContext

        public void TestContext(string context)
        {
            var ctx = new DataContext(context);

            ctx.GetTable<Person>().ToList();

            ctx.KeepConnectionAlive = true;

            ctx.GetTable<Person>().ToList();
            ctx.GetTable<Person>().ToList();

            ctx.KeepConnectionAlive = false;

            using (var tran = new DataContextTransaction(ctx))
            {
                ctx.GetTable<Person>().ToList();

                tran.BeginTransaction();

                ctx.GetTable<Person>().ToList();
                ctx.GetTable<Person>().ToList();

                tran.CommitTransaction();
            }
        }
开发者ID:ili,项目名称:linq2db,代码行数:25,代码来源:DataContextTests.cs


示例10: CMetaobjectExtented

        public CMetaobjectExtented(Guid ID, DataContext Context)
            : base(ID, Context)
        {
            this._likesNumberAttribute.Attributes = this._attributes;

            this.LikesNumber = 0;
        }
开发者ID:cMenu,项目名称:cMenu.Server,代码行数:7,代码来源:CMetaobjectExtented.cs


示例11: AmountInsert

        public int AmountInsert(DataContext Context)
        {
            var Amounts = Context.GetTable<CMenuServiceOrderAmount>();
            Amounts.InsertOnSubmit(this);

            return CErrors.ERR_SUC;
        }
开发者ID:cMenu,项目名称:cMenu.Server,代码行数:7,代码来源:CMenuServiceOrderAmount.cs


示例12: Test2

        public void Test2()
        {
            var dc = new DataContext();
            dc.AddTable("data", new[] {
                new Item { Col1="A", Col2 = 2 }
            });

            var flow = new Flow { Orientation = FlowOrientation.Vertical };
            var table = flow.AddTable<Item>("data");
            table.Columns.Single(a => a.DataField == "Col2").ConditionalFormatting = (value) => {
                if (!(value is int))
                    return null;
                var v = (int)value;
                if (v > 0)
                    return new Styling.CellStyle
                    {
                        FontStyle = new Styling.FontStyle
                        {
                            FontColor = Styling.Color.FromHtml("#00FF00")
                        }
                    };
                return null;
            };

            var rep = Report.CreateReport(flow, dc);
            var cells = ReportUtil.GetCellMatrix(rep);

            Assert.IsNull(cells[0][0].CustomStyle);
            Assert.IsNotNull(cells[0][1].CustomStyle);

            var html = HtmlReportWriter.RenderReport(rep, new DefaultHtmlReportTheme());
            Assert.IsTrue(html.Contains("style=\"color:"));
            Assert.IsTrue(html.Contains("#00FF00"));
        }
开发者ID:elea30,项目名称:codereports,代码行数:34,代码来源:ConditionalFormattingTest.cs


示例13: BlogsByUserViewModel

        public BlogsByUserViewModel(string username)
        {
            // Get back to the original name before url conversion
            BlogUsername = username.Replace(ContentGlobals.BLOGDELIMMETER, " ");

            using (var context = new DataContext())
            {

                // Get User based on authorid
                TheBlogUser = context.BlogUsers.FirstOrDefault(x => x.Username == BlogUsername);

                MaxBlogCount = BlogListModel.GetBlogSettings().MaxBlogsOnHomepageBeforeLoad;
                BlogTitle = BlogListModel.GetBlogSettings().BlogTitle;

                BlogsByUser = context.Blogs.Where(x => x.Author == BlogUsername && x.IsActive)
                            .OrderByDescending(blog => blog.Date)
                            .Take(MaxBlogCount)
                            .ToList();

                // Try permalink first
                TheBlog = BlogsByUser.FirstOrDefault(x => x.Author == BlogUsername);

                if (BlogsByUser.Count > 0)
                {
                    LastBlogId = BlogsByUser.LastOrDefault().BlogId;
                }
            }
        }
开发者ID:marciocamello,项目名称:dirigo-edge,代码行数:28,代码来源:BlogsByUserViewModel.cs


示例14: LinkInsert

        public int LinkInsert(DataContext Context)
        {
            var Links = Context.GetTable<CRdsAttributeLink>();
            Links.InsertOnSubmit(this);

            return -1;
        }
开发者ID:cMenu,项目名称:cMenu.Server,代码行数:7,代码来源:CRdsAttributeLink.cs


示例15: buscarporId

        //cambBuscar
        //*creavuelo
        public Vuelo buscarporId(int idVuelo)
        {
            Vuelo vuelo = new Vuelo();
            MyConnection myConnection = new MyConnection();

            DataContext datacontext = new DataContext(myConnection.SQLConnection);

            var Table = datacontext.GetTable<Vuelo>();

            try
            {
                var buscarPorIdVuelo = from vueloId in Table
                                       where vueloId.IdVuelo == idVuelo
                                       select vueloId;
                foreach (Vuelo v in buscarPorIdVuelo)
                {
                    vuelo = v;
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return vuelo;
        }
开发者ID:jennchinchi,项目名称:Proyecto-2-Progra-3,代码行数:29,代码来源:VueloDaImpl.cs


示例16: DataObjectQuery_Should_Select_All_Items_From_Database_With_Parameter_Binding_And_Context_Transaction

        public void DataObjectQuery_Should_Select_All_Items_From_Database_With_Parameter_Binding_And_Context_Transaction()
        {
            commandMock.Setup(c => c.CommandText).Returns("SELECT [Id], [Name], [FirstFlight] FROM Airplane WHERE Name = @Name");

            using (var context = new DataContext())
            {
                // Execute a command to open transaction.
                context.Execute("DELETE FROM Airplane");

                // Simulate connection open state later the first execute.
                connectionMock.Setup(c => c.State).Returns(ConnectionState.Open);

                select.With(context).All("WHERE Name = @Name", new { Name = "Omega" });

                context.Commit();
            }

            connectionMock.Verify(c => c.CreateCommand(), Times.Exactly(2));
            connectionMock.Verify(c => c.Open(), Times.Once());
            connectionMock.Verify(c => c.BeginTransaction(), Times.Once());
            connectionMock.Verify(c => c.Close(), Times.Once());
            commandMock.Verify(c => c.ExecuteReader(), Times.Once());
            commandMock.VerifySet(c => c.CommandText = "SELECT [Id], [Name], [FirstFlight] FROM Airplane WHERE Name = @Name");
            commandMock.VerifySet(c => c.Connection = connectionMock.Object);
            commandMock.VerifySet(c => c.Transaction = transactionMock.Object);
            commandMock.Verify(c => c.CreateParameter(), Times.Once());
            parameterMock.VerifySet(p => p.ParameterName = "@Name");
            parameterMock.VerifySet(p => p.Value = "Omega");
            parameterCollectionMock.Verify(p => p.Add(parameterMock.Object), Times.Once());
            transactionMock.Verify(t => t.Commit(), Times.Once());
        }
开发者ID:alexandreubaldo,项目名称:Thunderstruck,代码行数:31,代码来源:DataObjectQueryTest.cs


示例17: AuthorizationRepository

        public AuthorizationRepository()
        {
            _dataContext = new DataContext();
            var userStore = new UserStore<PropertyManagerUser>(_dataContext);
            _userManager = new UserManager<PropertyManagerUser>(userStore);

        }
开发者ID:RickNog,项目名称:16-PropertyManager,代码行数:7,代码来源:AuthorizationRepository.cs


示例18: GetUserId

 /// <summary>
 /// Metoda pobierająca id użytkownika na podstawie jego maila
 /// </summary>
 /// <param name="email"></param>
 /// <returns></returns>
 public int GetUserId(string email)
 {
     using (var context = new DataContext())
     {
         return context.Table<Users>().NewQuery().Where(x => x.Email == email).Select(x => x.ID).FirstOrDefault();
     }
 }
开发者ID:pmatwiejuk,项目名称:Mashup,代码行数:12,代码来源:AccountService.cs


示例19: SaveUser

        /// <summary>
        /// Metoda zapisująca informacje o użytkowniku
        /// </summary>
        /// <param name="email"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public bool SaveUser(string email, Users result)
        {
            try
            {
                using (var context = new DataContext())
                {
                    var user = context.Table<Users>().NewQuery().FirstOrDefault(x => x.Email == email);
                    if (user != null)
                    {
                        user.Name = result.Name;
                        user.Surname = result.Surname;
                        if (!string.IsNullOrEmpty(result.Password))
                        {
                            user.Password = result.Password;
                        }

                        context.Table<Users>().Update(user);
                        context.SaveChanges();

                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                // ojojojoj
            }

            return false;
        }
开发者ID:pmatwiejuk,项目名称:Mashup,代码行数:36,代码来源:AccountService.cs


示例20: DeleteRole

 public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
 {
     if (string.IsNullOrEmpty(roleName))
     {
         return false;
     }
     using (DataContext Context = new DataContext())
     {
         Role Role = null;
         Role = Context.Roles.FirstOrDefault(Rl => Rl.RoleName == roleName);
         if (Role == null)
         {
             return false;
         }
         if (throwOnPopulatedRole)
         {
             if (Role.Users.Any())
             {
                 return false;
             }
         }
         else
         {
             Role.Users.Clear();
         }
         Context.Roles.Remove(Role);
         Context.SaveChanges();
         return true;
     }
 }
开发者ID:dimonKomaran,项目名称:course,代码行数:30,代码来源:CodeFirstRoleProvider.cs



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C# DataContextChangedEventArgs类代码示例发布时间:2022-05-24
下一篇:
C# DataContainer类代码示例发布时间: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