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


C# ApplicationDbContext.Dispose方法代码示例

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


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

示例1: NewMessage

 public static void NewMessage(int id, string href, string userId)
 {
     using (var db = new ApplicationDbContext())
     {
         var ft = db.tForumMessages.Find(id);
         var t = new tNotification
         {
             tNotificationType = db.tNotificationType.Find(3),
             tNotification_date = System.DateTime.Now,
             tNotification_IsRead = false,
             tNotification_message =
                 "Новое сообщение на форуме " + ft.tForumThemes.tForumList.tForumList_name + " в разделе " + "\"" +
                 ft.tForumThemes.tForumThemes_name + "\"",
             tNotification_href = href
         };
         //Отсылаем модераторам
         foreach (var item2 in db.Roles.Where(a => a.Name == "moderator").SelectMany(item => item.Users.Where(a => a.UserId != userId)))
         {
             t.tUsers = db.Users.Find(item2.UserId);
             db.tNotification.Add(t);
             db.SaveChanges();
         }
         foreach (var item in ft.tForumThemes.tForumMessages.Select(a => a.tUsers).Distinct().Where(a => a.Id != userId).Where(item => !db.tNotification.Where(a => a.tUsers.Id == item.Id)
             .Any(a => a.tNotification_href == t.tNotification_href)))
         {
             t.tUsers = db.Users.Find(item.Id);
             db.tNotification.Add(t);
             db.SaveChanges();
         }
         //а теперь отошлем email
         var emList = new List<string>();
         var emailList = ft.tForumThemes.tForumMessages;
         var roleId = db.Roles.First(a => a.Name == "user").Id;
         foreach (var item in emailList.Where(a => a.tUsers.Id != userId).Where(a => a.tUsers.Roles.Any(b=> b.RoleId == roleId)))
         {
             emList.AddIfNotExists(item.tUsers.Email);
         }
         if (emList.Count() != 0)
         {
             var mm = new MailMessage
             {
                 IsBodyHtml = true,
                 Body =
                     "<h4>Форум Талисман-SQL</h4>" + "Появилось новоое сообщение на форуме " +
                     ft.tForumThemes.tForumList.tForumList_name + " в разделе " +
                     ft.tForumThemes.tForumThemes_name + "<p>" + href + "</p>",
                 Subject = "Новое сообщение на форуме Talisman-SQL"
             };
             foreach (var item in emList)
             {
                 mm.To.Add(item);
             }
             Code.Mail.SendEmail(mm);
         }
         db.Dispose();
     }
 }
开发者ID:nigihayami,项目名称:TalismanSqlForum,代码行数:57,代码来源:Notify.cs

示例2: BeginExecute

        protected override IAsyncResult BeginExecute(RequestContext requestContext, AsyncCallback callback, object state)
        {
            var dbContext = new ApplicationDbContext();

            this.UserProfile = dbContext.Users.FirstOrDefault(u => u.UserName == requestContext.HttpContext.User.Identity.Name);

            dbContext.Dispose();

            return base.BeginExecute(requestContext, callback, state);
        }
开发者ID:IvoPaunov,项目名称:Course-Project-ASP.NET-MVC,代码行数:10,代码来源:BaseController.cs

示例3: WinAution

 // GET: Auction/Create
 public ActionResult WinAution()
 {
     ApplicationDbContext db = new ApplicationDbContext();
     var email = db.Users.Where(e => e.UserName == User.Identity.Name).FirstOrDefault().Email;
     var proxy = new AuctionServiceClient("BasicHttpBinding_IAuctionService");
     proxy.Open();
     var items = proxy.GetMyWonAuctionsHistory(email);
     proxy.Close();
     db.Dispose();
     return View(items);
 }
开发者ID:toantruonggithub,项目名称:sguwcfstore,代码行数:12,代码来源:AuctionController.cs

示例4: SetView

 public static void SetView(string ip)
 {
     //Общее количество просмотров
     using (var db = new ApplicationDbContext())
     {
         if (!db.StatForum.Any(a => a.StatForumIp == ip))
         {
             var t = new StatForum { StatForumIp = ip };
             db.StatForum.Add(t);
             db.SaveChanges();
         }
         db.Dispose();
     }
 }
开发者ID:nigihayami,项目名称:TalismanSqlForum,代码行数:14,代码来源:Stat.cs

示例5: SetViewList

 public static void SetViewList(string ip, int id)
 {
     //Количество просмотров конкретного форума
     using (var db = new ApplicationDbContext())
     {
         if (!db.StatForumList.Where(a => a.TForumLists.Id == id).Any(a => a.StatForumIp == ip))
         {
             var t = new StatForumList { StatForumIp = ip, TForumLists = db.tForumLists.Find(id) };
             db.StatForumList.Add(t);
             db.SaveChanges();
         }
         db.Dispose();
     }
 }
开发者ID:nigihayami,项目名称:TalismanSqlForum,代码行数:14,代码来源:Stat.cs

示例6: Index

        // GET: Auction
        public ActionResult Index()
        {
            List<Auction> items;

            var proxy = new AuctionServiceClient("BasicHttpBinding_IAuctionService");
            proxy.Open();
            ApplicationDbContext db = new ApplicationDbContext();
            var email = db.Users.Where(e => e.UserName == User.Identity.Name).FirstOrDefault().Email;
            items = proxy.GetMyAuctions(email).ToList();
            ViewData["groups"] = proxy.GetAllCategories().Select(e => e.Name).ToList();
            proxy.Close();
            db.Dispose();
            return View(items);
        }
开发者ID:toantruonggithub,项目名称:sguwcfstore,代码行数:15,代码来源:AuctionController.cs

示例7: AddPlayer

        // GET: Player
        public ActionResult AddPlayer(PlayerViewModel player)
        {
            if (player != null)
            {

                using (ApplicationDbContext ctx = new ApplicationDbContext())
                {
                    Player addPlayer = new Player
                    {
                        Name = player.Name,
                        PhoneNumber = player.PhoneNumber,
                        Email = player.Email

                    };

                    ctx.Player.Add(addPlayer);
                    ctx.SaveChanges();

                    if (player.Wednesday.Equals(true))
                    {
                        ctx.Players_GameType.Add(new Players_GameType
                        {
                            PlayerID = addPlayer.ID,
                            GameTypeID = 2,
                            IsSubstitute = true
                        });

                        ctx.SaveChanges();

                        if (player.Sunday.Equals(true))
                        {
                            ctx.Players_GameType.Add(new Players_GameType
                            {
                                PlayerID = addPlayer.ID,
                                GameTypeID = 1,
                                IsSubstitute = true
                            });

                            ctx.SaveChanges();
                        }

                        ctx.Dispose();
                    }
                }

            }
            return View();
        }
开发者ID:dtoliveira,项目名称:topsunday,代码行数:49,代码来源:PlayerController.cs

示例8: Application_Start

        protected void Application_Start()
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<Models.HotelPuraVidaContext,Migrations.Configuration>());

            ApplicationDbContext db = new ApplicationDbContext();
            //comentar CreateRoles
            CreateRoles(db);
            CreateAdministrador(db);
            AddPermisionToADM(db);
            db.Dispose();

            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
开发者ID:CRprogrammer,项目名称:HotelPuraVida,代码行数:17,代码来源:Global.asax.cs

示例9: ObtenerProfesores

        /// <summary>
        /// Método para obtener todos los usuarios con rol de profesor
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Usuario> ObtenerProfesores()
        {
            List<Usuario> profesores = new List<Usuario>();
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                //Obtenemos Users que están en rol Profesor
                IdentityRole rolProfesor = db.Roles.Where(x => x.Name =="Profesor").FirstOrDefault();
                var rolesUsuarios = db.UserRoles.Where(x => x.RoleId == rolProfesor.Id).ToList();
                foreach (var item in rolesUsuarios)
                {
                    IdentityUser usuario = db.Users.Where(x => x.Id == item.UserId).FirstOrDefault();
                    profesores.Add(db.Usuario.Where(x => x.NombreDeUsuario == usuario.UserName).FirstOrDefault());
                }
                db.Dispose();
            }
            return profesores;

        }
开发者ID:CarlosOlivares,项目名称:web,代码行数:22,代码来源:GestionDeUsuario.cs

示例10: Application_Start

        protected void Application_Start()
        {
            //Cada vez que se inicia verifica si el modelo cambio
            Database.SetInitializer(
                new MigrateDatabaseToLatestVersion<Models.POS_PointOfSaleContext,
                Migrations.Configuration>());
            //conectar a la base
            ApplicationDbContext db = new ApplicationDbContext();
            CreateRoles(db);
            CreateSuperUser(db);
            AddPermisionsToSuperuser(db);
            db.Dispose();

            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
开发者ID:yuuki16,项目名称:POS,代码行数:19,代码来源:Global.asax.cs

示例11: OnAuthentication

        public void OnAuthentication(AuthenticationContext filterContext)
        {
            IIdentity ident = filterContext.Principal.Identity;
            ApplicationDbContext dbContext = new ApplicationDbContext();
            string sTourId = filterContext.Controller.ValueProvider.GetValue("tourId").AttemptedValue;
            int tourId;
            string userId = ident.GetUserId();

            Int32.TryParse(sTourId, out tourId);

            var userRow = dbContext.TournamentUsers
                .Where(x => x.TournamentId == tourId)
                .Where(x => x.UserId == userId)
                .FirstOrDefault();

            if (userRow == null)
                filterContext.Result = new HttpUnauthorizedResult();

            dbContext.Dispose();
        }
开发者ID:mknizewski,项目名称:SAP,代码行数:20,代码来源:TournamentsAuth.cs

示例12: Index

        //private ApplicationDbContext db = new ApplicationDbContext();
        public ActionResult Index()
        {
            using(ApplicationDbContext db = new ApplicationDbContext()){
                try{
                Resume resume = db.Resumes.SingleOrDefault(i=>i.Id > 0);
                    if (resume != null)
                    {
                        string result = JsonConvert.SerializeObject(resume);
                        return Json(result, JsonRequestBehavior.AllowGet);
                    }
                    else return new HttpNotFoundResult("Could not find a resume");
                }
                catch(Exception E){
                    return new HttpNotFoundResult("Exception Thrown: " + E.Message);

                }
                finally{
                    db.Dispose ();
                }
            }
        }
开发者ID:dboelens,项目名称:DanielBoelensWebsite,代码行数:22,代码来源:ResumeController.cs

示例13: Application_Start

        protected void Application_Start()
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<Models.EmilioMarketContext, Migrations.Configuration>());
            
            //Me conecto a las tablas de seguridad a la base de datos:
            ApplicationDbContext db = new ApplicationDbContext ();
            //Inicio Método Crear Roles:
            CreateRoles(db);
            //Método para crear SuperUsuarios:
            CreateSuperUser(db);
            //Método para adiccionar permisos al superUser:
            AddPermissionToSuperUser(db);
            //Close DB:
            db.Dispose();

            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
开发者ID:emiliobs,项目名称:EmilioMarket,代码行数:21,代码来源:Global.asax.cs

示例14: Login

 public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
 {
     if (!ModelState.IsValid) return View(model);
     var user = await UserManager.FindAsync(model.Email, model.Password);
     if (user != null)
     {
         await SignInAsync(user, model.RememberMe);
         using (var db = new ApplicationDbContext())
         {
             var t = db.Users.First(a => a.Email == model.Email);
             if (t != null)
             {
                 t.LastIn = DateTime.Now;
                 db.Entry(t).State = System.Data.Entity.EntityState.Modified;
                 db.SaveChanges();
             }
             db.Dispose();
         }
         if (HttpRuntime.Cache["LoggedInUsers"] != null) //if the list exists, add this user to it
         {
             //get the list of logged in users from the cache
             var loggedInUsers = (List<string>)HttpRuntime.Cache["LoggedInUsers"];
             //add this user to the list
             loggedInUsers.Add(model.Email);
             //add the list back into the cache
             HttpRuntime.Cache["LoggedInUsers"] = loggedInUsers;
         }
         else //the list does not exist so create it
         {
             //create a new list
             var loggedInUsers = new List<string> {model.Email};
             //add this user to the list
             //add the list into the cache
             HttpRuntime.Cache["LoggedInUsers"] = loggedInUsers;
         }
         return RedirectToLocal(returnUrl);
     }
     ModelState.AddModelError("", "Недопустимое имя пользователя или пароль.");
     return View(model);
 }
开发者ID:nigihayami,项目名称:TalismanSqlForum,代码行数:40,代码来源:AccountController.cs

示例15: SyncBranch

        static void SyncBranch(string username)
        {
            using (var db = new ApplicationDbContext())
            {
                var t = db.tModerator.First(a => a.tUsers.UserName == username);
                if (t != null)
                {
                    var fc = new FbConnectionStringBuilder
                    {
                        UserID = t.tModerator_userId,
                        Password = t.tModerator_password,
                        Database = t.tModerator_database,
                        Charset = "win1251",
                        Pooling = false,
                        Role = "R_ADMIN"
                    };

                    using (var fb = new FbConnection(fc.ConnectionString))
                    {
                        try
                        {
                            fb.Open();
                            using (var ft = fb.BeginTransaction())
                            {
                                using (var fcon = new FbCommand("select b.id_branch, b.mnemo from branch b", fb, ft))
                                {
                                    using (var fr = fcon.ExecuteReader())
                                    {
                                        while (fr.Read())
                                        {
                                            if (db.tBranch.Find(fr[0]) != null)
                                            {
                                                var m = db.tBranch.Find(fr[0]);
                                                m.tBranch_name = fr[1].ToString();
                                                db.Entry(m).State = System.Data.Entity.EntityState.Modified;
                                                db.SaveChanges();
                                            }
                                            else
                                            {
                                                var m = new tBranch { Id = (int)fr[0], tBranch_name = fr[1].ToString() };
                                                db.tBranch.Add(m);
                                                db.SaveChanges();
                                            }
                                        }
                                        fr.Dispose();
                                    }
                                    fcon.Dispose();
                                }
                                ft.Commit();
                                ft.Dispose();
                            }
                        }
                        catch
                        {
                            //Пропускаем все ошибки - сихн е удалась
                        }
                        finally
                        {
                            fb.Close();
                        }
                        fb.Dispose();
                    }
                }
                db.Dispose();
            }
        }
开发者ID:nigihayami,项目名称:TalismanSqlForum,代码行数:66,代码来源:AdminBtController.cs


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