Example #1
0
 public void AddList(Cell[,] gameField, int TypeGame, int Iter)
 {
     using (var db = new DataModelContainer())
     {
         var game = new Game()
         {
             Type = TypeGame, SizeX = gameField.Length / gameField.GetLength(0), SizeY = gameField.GetLength(0), Iteration = Iter
         };
         db.GameSet.Add(game);
         Coords coord;
         for (int i = 0; i < gameField.Length / gameField.GetLength(0); i++)
         {
             for (int j = 0; j < gameField.GetLength(0); j++)
             {
                 if (gameField[i, j] != null)
                 {
                     coord = new Coords()
                     {
                         CoordX = gameField[i, j].CoordX, CoordY = gameField[i, j].CoordY, TypeLiving = (int)gameField[i, j].livingName, Game = game
                     };
                     db.CoordsSet.Add(coord);
                 }
             }
         }
         db.SaveChanges();
     }
 }
Example #2
0
        public int addRate(int userId, int movieId, int rateValue)
        {
            using (var db = new DataModelContainer())
            {
                db.Database.Connection.Open();

                var myRate = new Rate()
                {
                    rate    = rateValue,
                    UserId  = userId,
                    MovieId = movieId
                };

                db.Entry(myRate).State = System.Data.Entity.EntityState.Added;
                int res = db.SaveChanges();

                if (res > 0)
                {
                    MessageBox.Show("successfuly add rate");
                    return(res);
                }
                else
                {
                    MessageBox.Show("Error can't add rate to the movie");
                    return(res);
                }
            }
        }
Example #3
0
        public ActionResult Create(UserInfo userInfo)
        {
            DataModelContainer dbContext = new DataModelContainer();

            dbContext.UserInfo.Add(userInfo);
            dbContext.SaveChanges();
            return(RedirectToAction("Index"));
        }
Example #4
0
        public User CreateUser(User user)
        {
            DataModelContainer ctx = DataModelContainer.GetDb();

            Console.WriteLine("user in create: " + user.Login);
            ctx.UserSet.Add(user);
            ctx.SaveChanges();
            return(user);
        }
        // 实现对数据库的添加功能,添加实现EF框架的引用

        public T AddEntity(T entity)
        {
            //EF4.0的写法   添加实体

            //db.CreateObjectSet<T>().AddObject(entity);

            //EF5.0的写法

            db.Entry <T>(entity).State = EntityState.Added;



            //下面的写法统一

            db.SaveChanges();

            return(entity);
        }
Example #6
0
        public bool DeleteComment(Comment comment)
        {
            DataModelContainer ctx      = DataModelContainer.GetDb();
            Comment            toDelete = ctx.CommentSet.Where(c => c.Id == comment.Id).FirstOrDefault();

            ctx.CommentSet.Remove(toDelete);
            ctx.SaveChanges();
            return(true);
        }
Example #7
0
        public bool DeleteMovie(Movie movie)
        {
            DataModelContainer ctx = new DataModelContainer();
            Movie toDelete         = ctx.MovieSet.Where(m => m.Id == movie.Id).FirstOrDefault();

            ctx.MovieSet.Remove(toDelete);
            ctx.SaveChanges();
            return(true);
        }
Example #8
0
        public Movie CreateMovie(Movie movie)
        {
            DataModelContainer ctx = new DataModelContainer();

            Console.WriteLine("movie in create: " + movie.Title);
            ctx.MovieSet.Add(movie);
            ctx.SaveChanges();
            return(movie);
        }
Example #9
0
        public bool DeleteUser(User user)
        {
            DataModelContainer ctx = DataModelContainer.GetDb();
            User toDelete          = ctx.UserSet.Where(u => u.Id == user.Id).FirstOrDefault();

            ctx.UserSet.Remove(toDelete);
            ctx.SaveChanges();
            return(true);
        }
Example #10
0
        public Comment CreateComment(Comment comment)
        {
            DataModelContainer ctx = new DataModelContainer();

            Console.WriteLine("comment in create: " + comment.Message);
            ctx.CommentSet.Add(comment);
            ctx.SaveChanges();
            return(comment);
        }
 public ActionResult EditingInline_Create([DataSourceRequest] DataSourceRequest request, VideoViewModel video)
 {
     if (video != null && ModelState.IsValid)
     {
         Video modelVideo = video.ToVideo();
         db.Videos.Add(modelVideo);
         try
         {
             db.SaveChanges();
         }
         catch (Exception ex)
         {
             ModelState.AddModelError("", ex.Message);
         }
         return(Json(new[] { VideoViewModel.From(modelVideo) }.ToDataSourceResult(request, ModelState)));
     }
     // This has to get fixed to display a fail.
     return(Json(new[] { video }.ToDataSourceResult(request, ModelState)));;
 }
 public ActionResult AddVideoToCourse(int courseId, int videoSelected)
 {
     if (!db.CourseVideos.Any(cv => cv.CourseId == courseId && cv.VideoId == videoSelected))
     {
         int position = 0;
         if (db.CourseVideos.Any(cv => cv.CourseId == courseId))
         {
             //Get max position
             position = db.CourseVideos.Where(cv => cv.CourseId == courseId).Max(cv => cv.Position);
         }
         var newCv = db.CourseVideos.Create();
         newCv.CourseId = courseId;
         newCv.VideoId  = videoSelected;
         newCv.Position = ++position;
         db.CourseVideos.Add(newCv);
         db.SaveChanges();
     }
     return(RedirectToAction("Videos", new { courseId = courseId }));
 }
Example #13
0
        public Comment CreateComment(Comment comment)
        {
            DataModelContainer ctx = DataModelContainer.GetDb();

            Console.WriteLine("comment in create: " + comment.ToString());
            ctx.MovieSet.Attach(comment.Movie);
            ctx.UserSet.Attach(comment.User);
            ctx.CommentSet.Add(comment);
            ctx.SaveChanges();
            return(comment);
        }
Example #14
0
        public int UpdateClass(List <string> ID)
        {
            if (ID == null)
            {
                return(0);
            }

            foreach (string id in ID)
            {
                //需要修改的實體
                var staff = dbContext.Staff.FirstOrDefault(m => m.ID == id);
                if (staff != null)
                {
                    Staff newstaff = new Staff();
                    newstaff       = staff;
                    newstaff.CLASS = staff.CLASS == "白班" ? "晚班" : "白班";  //換班
                    dbContext.Entry(staff).CurrentValues.SetValues(newstaff);
                }
            }
            return(dbContext.SaveChanges());
        }
Example #15
0
        public ActionResult Index(string NewPassword)
        {
            string LoginName = Session["userPhone"] == null ? Session["userName"].ToString() : Session["userPhone"].ToString();

            if (Session["userPhone"] == null)
            {
                var admin = dbContext.AdminInfo.Where(a => a.AdminName == LoginName).FirstOrDefault();
                //int id = admin.Id;
                admin.AdminPwd = NewPassword;
                dbContext.Entry(admin).State = System.Data.Entity.EntityState.Modified;
                dbContext.SaveChanges();
            }
            else
            {
                var user = dbContext.UserInfo.Where(u => u.UPhone == LoginName).FirstOrDefault();
                user.UPwd = NewPassword;
                dbContext.Entry(user).State = System.Data.Entity.EntityState.Modified;
                dbContext.SaveChanges();
            }
            return(RedirectToAction("Index", "Index"));
        }
Example #16
0
 /// <summary>
 /// Adds the specified element.
 /// </summary>
 /// <param name="element">The element.</param>
 /// <returns></returns>
 /// 创建者:叶烨星
 /// 创建时间:2018/1/28 18:53
 /// 修改者:
 /// 修改时间:
 public ServiceResult <bool> Add(T element)
 {
     db.Set <T>().Add(element);
     try
     {
         db.SaveChanges();
         return(new ServiceResult <bool>
         {
             Result = true,
             State = true
         });
     }
     catch (Exception e)
     {
         return(new ServiceResult <bool>
         {
             State = false,
             Message = e.ToString()
         });
     }
 }
Example #17
0
        internal static void Save(Person newPerson)
        {
            DataModelContainer ctx = new DataModelContainer();
            User user = new User();

            user.Login    = newPerson.Login;
            user.Password = newPerson.Password;

            ctx.UserSet.Add(user);
            //var query = ctx.UserSet.Where(u => u.Login.Contains("i")).ToList();
            var query = ctx.UserSet.ToList();

            ctx.SaveChanges();
        }
Example #18
0
        public static void SendPrivateMessageToClients(object data)
        {
            Message mess = (Message)data;

            if (mess.UserTo_Id != null) // шлем личное сообщение пользователю
            {
                ClientInfo clientTo = listClients.FirstOrDefault(x => x.UserId == mess.UserTo_Id);
                if (clientTo != null)
                {
                    bool res = clientTo.callback.ReceivePrivateMessage(GetLoginFrom(mess), GetLoginTo(mess), mess.Text, mess.Date);
                    if (res)
                    {
                        using (var db = new DataModelContainer())
                        {
                            Message message = db.Messages.FirstOrDefault(x => x.Id == mess.Id);
                            message.IsRead          = true;
                            db.Entry(message).State = System.Data.Entity.EntityState.Modified;
                            db.SaveChanges();
                        }
                    }
                }
                ClientInfo clientFrom = listClients.FirstOrDefault(x => x.UserId == mess.UserFrom_Id);
                if (clientFrom != null && clientFrom != clientTo)
                {
                    clientFrom.callback.ReceivePrivateMessage(GetLoginFrom(mess), GetLoginTo(mess), mess.Text, mess.Date);
                }
            }
            else if (mess.GroupTo_Id != null) //шлем групповое сообщение
            {
                using (var db = new DataModelContainer())
                {
                    Group grp = db.Groups.FirstOrDefault(x => x.Id == mess.GroupTo_Id);
                    foreach (var us in grp.User)
                    {
                        ClientInfo client = listClients.FirstOrDefault(x => x.UserId == us.Id);
                        if (client != null)
                        {
                            bool res = client.callback.ReceivePrivateMessage(GetLoginFrom(mess), GetGroupTo(mess), mess.Text, mess.Date);
                            if (res)
                            {
                                ReadMessage rm = db.ReadMessages.FirstOrDefault(x => x.Message_Id == mess.Id && x.User_Id == client.UserId);
                                rm.IsRead          = true;
                                db.Entry(rm).State = System.Data.Entity.EntityState.Modified;
                            }
                        }
                    }
                    db.SaveChanges();
                }
            }
        }
Example #19
0
        public void SendPublicMessage(int idUserFrom, string message)
        {
            using (DataModelContainer db = new DataModelContainer())
            {
                Message mess = new Message {
                    UserFrom_Id = idUserFrom, UserTo_Id = null, GroupTo_Id = null, Text = message, Date = DateTime.Now, IsRead = null
                };
                db.Messages.Add(mess);
                db.SaveChanges();

                Thread thread = new Thread(new ParameterizedThreadStart(Clients.SendPublicMessageToClients));
                thread.IsBackground = true;
                thread.Start(mess);
            }
        }
Example #20
0
        /// <summary>
        /// 批量添加 數據
        /// </summary>
        /// <param name="ID">工號數組</param>
        /// <param name="state">出勤狀態數組</param>
        /// <returns>添加數據的數量</returns>
        public int add_Attendance(List <string> ID, List <string> state)
        {
            int count = 0;

            foreach (string id in ID)
            {
                var temp = dbContext.Staff.FirstOrDefault(u => u.ID == id);
                {
                    Attendance a = new Attendance();
                    a.ID       = temp.ID;
                    a.NAME     = temp.NAME;
                    a.BU       = temp.BU;
                    a.LINENAME = temp.LINENAME;
                    a.CLASS    = temp.CLASS;
                    a.state1   = state[count];
                    a.date1    = DateTime.Now;
                    //   a.date2 = null;a.note1 = null; a.note2 = null; a.reason2 = null;
                    dbContext.Attendance.Add(a);
                    //dbContext.SaveChanges();
                }
                count++;
            }
            return(dbContext.SaveChanges());
        }
Example #21
0
 public void RemoveList(int id)
 {
     using (var db = new DataModelContainer())
     {
         foreach (var item in db.CoordsSet.Where(x => x.Game.Id == id))
         {
             db.CoordsSet.Remove(item);
         }
         Game game = db.GameSet.Where(x => x.Id == id).FirstOrDefault();
         if (game != null)
         {
             db.GameSet.Remove(game);
         }
         db.SaveChanges();
     }
 }
Example #22
0
        internal static void Modif(User us)
        {
            DataModelContainer ctx = new DataModelContainer();
            User user = new User();

            var utilisateur = ctx.UserSet.Where(u => u.Connected == true).ToList();

            if (utilisateur.Count > 0)
            {
                user          = ctx.UserSet.Find(utilisateur[0].Id);
                user          = utilisateur[0];
                user.Login    = us.Login;
                user.Password = us.Password;
                //ctx.UserSet.(user);
                ctx.SaveChanges();
            }
        }
Example #23
0
 public static bool InsertClient(string name)
 {
     using (var context = new DataModelContainer())
     {
         try
         {
             Clients client = new Clients {
                 Name = name
             };
             context.Clients.Add(client);
             context.SaveChanges();
         }
         catch
         {
             return(false);
         }
         return(true);
     }
 }
Example #24
0
        public bool deleteCommentsByUser(int userId)
        {
            using (var db = new DataModelContainer())
            {
                db.Database.Connection.Open();

                var comments = (from r in db.CommentSet
                                where r.UserId == userId
                                select r).ToList();
                if (comments.Count < 1)
                {
                    return(false);
                }
                comments.ForEach(delegate(Comment comment) {
                    db.Entry(comment).State = System.Data.Entity.EntityState.Deleted;
                });
                return(db.SaveChanges() != 0);
            }
        }
Example #25
0
        /// <summary>
        /// 添加公司
        /// </summary>
        /// <param name="company">公司</param>
        /// <returns></returns>
        /// 创建者:叶烨星
        /// 创建时间:2018/1/23 20:47:
        /// 修改者:叶烨星
        /// 修改时间:2018/1/23 20:47
        public ServiceResult <bool> AddCompany(Company company)
        {
            if (company == null)
            {
                return(new ServiceResult <bool>
                {
                    State = false,
                    Message = "公司信息不能为空"
                });
            }

            db.Company.Add(company);
            db.SaveChanges();

            return(new ServiceResult <bool>
            {
                State = true,
                Result = true
            });
        }
Example #26
0
 public static bool DeleteClient(int id)
 {
     using (var context = new DataModelContainer())
     {
         try
         {
             var clientToRemove = new Clients {
                 ClientId = id
             };
             context.Clients.Attach(clientToRemove);
             context.Clients.Remove(clientToRemove);
             context.SaveChanges();
         }
         catch
         {
             return(false);
         }
         return(true);
     }
 }
Example #27
0
        private bool CanExecuteUserConnect(string Login, string Password)
        {
            var utilisateur = ctx.UserSet.Where(u => u.Login == Login && u.Password == Password).ToList();

            ctx.SaveChanges();

            if (utilisateur.Count > 0)
            //if ((Login.Text == "Bill") & (Password.Password == "test"))
            //if ((ctx.UserSet.Where(u => u.Login.Contains(Login.Text)).Where(u => u.Password.Contains(Password.Password)) )
            {
                Console.WriteLine("Co dans Model");


                return(true);
            }
            else
            {
                Console.WriteLine("Pas Co dans Model");
                return(false);
            }
        }
Example #28
0
        public Comment UpdateComment(Comment comment)
        {
            Console.WriteLine("Comment passed to update: " + comment.ToString());
            DataModelContainer ctx      = DataModelContainer.GetDb();
            Comment            toUpdate = ctx.CommentSet.Where(c => c.Id == comment.Id).FirstOrDefault();

            Console.WriteLine("In UpdateComment, return of update method: " + toUpdate.ToString());
            toUpdate.Message = comment.Message;
            toUpdate.Movie   = comment.Movie;
            toUpdate.Note    = comment.Note;
            toUpdate.User    = comment.User;
            if (toUpdate.Equals(comment))
            {
                Console.WriteLine("Update ok");
                ctx.SaveChanges();
                return(toUpdate);
            }
            else
            {
                throw new Exception("Update comment failed");
            }
        }
Example #29
0
        public Movie UpdateMovie(Movie movie)
        {
            Console.WriteLine("Movie passed to update: " + movie.ToString());
            DataModelContainer ctx = new DataModelContainer();
            Movie toUpdate         = ctx.MovieSet.Where(m => m.Id == movie.Id).FirstOrDefault();

            Console.WriteLine("In UpdateMovie, return of update method: " + toUpdate.ToString());
            toUpdate.Title    = movie.Title;
            toUpdate.Type     = movie.Type;
            toUpdate.Abstract = movie.Abstract;
            toUpdate.Comments = movie.Comments;
            if (toUpdate.Equals(movie))
            {
                Console.WriteLine("Update ok");
                ctx.SaveChanges();
                return(toUpdate);
            }
            else
            {
                throw new Exception("Update movie failed");
            }
        }
Example #30
0
        public User UpdateUser(User user)
        {
            Console.WriteLine("User passed to update: " + user.ToString());
            DataModelContainer ctx = DataModelContainer.GetDb();
            User toUpdate          = ctx.UserSet.Where(u => u.Id == user.Id).FirstOrDefault();

            Console.WriteLine("In UpdateUser, return of update method: " + toUpdate.ToString());
            toUpdate.Firstname = user.Firstname;
            toUpdate.Lastname  = user.Lastname;
            toUpdate.Login     = user.Login;
            toUpdate.Password  = user.Password;
            if (toUpdate.Equals(user))
            {
                Console.WriteLine("Update ok");
                ctx.SaveChanges();
                return(toUpdate);
            }
            else
            {
                throw new Exception("Update failed");
            }
        }
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindAsync(model.UserName, model.Password);
                if (user != null)
                {
                    await SignInAsync(user, model.RememberMe);
                    // Successful login here; do something...
                    try
                    {
                        // Update the last login time
                        DataModelContainer db = new DataModelContainer();
                        Guid userId = Guid.Parse(user.Id);
                        Logins l = db.Logins.Find(userId);
                        if (l == null)
                        {
                            l = new Logins();
                            l.Id = userId;
                            l.LastLoginTime = DateTime.UtcNow;
                            db.Logins.Add(l);
                        }
                        else
                        {
                            l.LastLoginTime = DateTime.UtcNow;
                        }
                        db.SaveChanges();

                        // Set the company name
                        //if (User.IsInRole(Constants.PARTNER_ADMIN))
                        {
                            PartnerStaffMember psmu = db.PartnerStaffMembers.Where(x => x.Id == userId).FirstOrDefault();
                            if (psmu != null)
                            {
                                Session["CompanyName"] = psmu.PartnerCompany.Name;
                            }
                            else
                            {
                                PartnerAdmin pau = db.PartnerAdmins.Where(x => x.Id == userId).FirstOrDefault();
                                if (pau != null)
                                {
                                    Session["CompanyName"] = pau.PartnerCompany.Name;
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                    
                    //return RedirectToLocal(returnUrl);
                    // Always go to Home
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", "Invalid username or password.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        public ActionResult InitDB()
        {
            DataModelContainer db = new DataModelContainer();
            bool needSaving = false;

            //-----------------------------------------------------------------
            if (!db.Genders.Any(g => g.Title == "Male"))
            {
                db.Genders.Add(new Gender() { Title = "Male" });
                needSaving = true;
            }
            if (!db.Genders.Any(g => g.Title == "Female"))
            {
                db.Genders.Add(new Gender() { Title = "Female" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            if (!db.Countries.Any(c => c.Name == "India"))
            {
                db.Countries.Add(new Country() { Id = "in", Name = "India" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            string[] items = new string[] {
                               "ap", "Andhra Pradesh", "in",      "up", "Uttar Pradesh", "in",
                               "ar", "Arunachal Pradesh", "in",   "cg", "Chhattisgarh", "in",
                               "as", "Assam", "in",               "tr", "Tripura", "in",
                               "br", "Bihar", "in",               "tn", "Tamil Nadu", "in",
                               "mh", "Maharashtra", "in",         "py", "Puducherry", "in",
                               "pb", "Punjab", "in",              "nl", "Nagaland", "in",
                               "sk", "Sikkim", "in",              "or", "Odisha", "in",
                               "ga", "Goa", "in",                 "ka", "Karnataka", "in",
                               "gj", "Gujarat", "in",             "hr", "Haryana", "in",
                               "hp", "Himachal Pradesh", "in",    "jk", "Jammu & Kashmir", "in",
                               "jh", "Jharkhand", "in",           "ka", "Karnataka", "in",
                               "rj", "Rajasthan", "in",           "ml", "Meghalaya", "in",
                               "kl", "Kerala", "in",              "mp", "Madhya Pradesh", "in",
                               "mn", "Manipur", "in",             "wb", "West Bengal", "in"
                             };
            for(int i=0; i<items.Length; i+=3)
            {
                string abbr = items[i], name = items[i+1], cid = items[i + 2];
                if (!db.States.Any(sx => sx.CountryId == cid && (sx.Abbr == abbr || sx.Name == name)))
                {
                    db.States.Add(new State() { Abbr = abbr, Name = name, CountryId = cid });
                    needSaving = true;
                }
            }
            if (needSaving)
            {
                db.SaveChanges();
                needSaving = false;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Unknown", "Not religious", "Hindu", "Muslim", "Christian", "Other" };
            foreach(string itm in items)
                if (!db.Religions.Any(r => r.Title == itm))
                {
                    db.Religions.Add(new Religion() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------------
            items = new string[] { /*"Not disabled",*/ "Deaf", "Dumb", "Blind", "Dysfunctional hand", "Dysfunctional leg", "Other"};
            foreach(string itm in items)
                if (!db.Disabilities.Any(d => d.Title == itm))
                {
                    db.Disabilities.Add(new Disability() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            if (!db.StaffTypes.Any(st => st.Title == "Field"))
            {
                db.StaffTypes.Add(new StaffType() { Title = "Field" });
                needSaving = true;
            }
            if (!db.StaffTypes.Any(st => st.Title == "Office"))
            {
                db.StaffTypes.Add(new StaffType() { Title = "Office" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            if (!db.Languages.Any(e => e.Title == "English"))
            {
                db.Languages.Add(new Language() { Title = "English" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Unknown", "Government school", "Private school", "Madrasa", "Anganwadi" };
            foreach (string itm in items)
                if (!db.SchoolTypes.Any(st => st.Title == itm))
                {
                    db.SchoolTypes.Add(new SchoolType() { Title = itm });
                    needSaving = true;
                }
            if (!db.SchoolTypes.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.SchoolTypes.Add(new SchoolType() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Unknown", "Schedule Caste (SC)", "Schedule Tribe (ST)", "Other Backward Caste (OBC)", "General" };
            foreach (string itm in items)
                if (!db.Castes.Any(c => c.Title == itm))
                {
                    db.Castes.Add(new Caste() { Title = itm });
                    needSaving = true;
                }

            //-----------------------------------------------------------------
            items = new string[] { "Unknown", "1", "2", "3", "4", "5", "8", "10", "12", "Graduate", "Illiterate" };
            foreach (string itm in items)
                if (!db.EducationLevels.Any(e => e.Title == itm))
                {
                    db.EducationLevels.Add(new EducationLevel() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            items = new string[] { "Unknown", "1", "2", "3", "4", "5", "8", "10", "12", "Graduate", "Illiterate" };
            foreach (string itm in items)
                if (!db.ClassLevels.Any(e => e.Title == itm))
                {
                    db.ClassLevels.Add(new ClassLevel() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            items = new string[] { "Unknown", "Son", "Daughter", "Brother", "Sister", "Grandchild", "In-law", "Niece", "Nephew", "Adopted" };
            foreach (string itm in items)
                if (!db.ChildRelationships.Any(r => r.Title == itm))
                {
                    db.ChildRelationships.Add(new ChildRelationship() { Title = itm });
                    needSaving = true;
                }
            if (!db.ChildRelationships.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.ChildRelationships.Add(new ChildRelationship() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Husband", "Wife", "Brother", "Sister", "Son", "Daughter", "Mother-in-Law", "Father-in-Law",
                                   "Daughter-in-Law", "Son-in-Law", "Sister-in-Law", "Brother-in-Law", "Niece", "Nephew", "Grandmother", "Grandfather" };
            foreach (string itm in items)
                if (!db.AdultRelationships.Any(r => r.Title == itm))
                {
                    db.AdultRelationships.Add(new AdultRelationship() { Title = itm });
                    needSaving = true;
                }
            if (!db.AdultRelationships.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.AdultRelationships.Add(new AdultRelationship() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Raised bed", /*"Bed net",*/ "Chair", /*"Mirror",*/ "Mobile phone", /*"Telephone (land line)",*/ "Refrigerator",
                "Storage drum", "Cook stove", "Door with lock", /*"Window with lock",*/ "Television", "VCR/DVD/VCD", "Bicycle", "Car",
                "MC/scooter", "Generator", /*"Inverter",*/ "Almira", "Pressure cooker/pan", "Casserole/thermos/thermoware", /*"Pushcard/rickshaw",*/
                "Sawing machine", /*"Electric fan",*/ "Chicken", "Goats/pig", "Cow (female, dairy)", "Cow (male)", "Buffalo", "Room", "Radio",
                // Partner specific?
                "Plow", "Diesel pump", "Loom (hand)", "Loom (powered)", "Warping machine", "Spindle", "Bobbin", "Shuttle"
            };
            foreach (string itm in items)
                if (!db.AssetTypes.Any(e => e.Title == itm))
                {
                    db.AssetTypes.Add(new AssetType() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            items = new string[] { "Rice", "Roti", "Leafy Vegetables", "Potato", "Cauliflower", "Tomato" };
            foreach (string itm in items)
                if (!db.MealTypes.Any(mt => mt.Title == itm))
                {
                    db.MealTypes.Add(new MealType() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            items = new string[] { "Kirana Shop", "Fair Price Shop (Ration Shop)", "Weekly Village Market", "Local Mandi" };
            foreach (string itm in items)
                if (!db.FoodSourceTypes.Any(fs => fs.Title == itm))
                {
                    db.FoodSourceTypes.Add(new FoodSourceType() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            items = new string[] { "Unknown", "Under 0.5km", "0.5 - 2km", "2 - 7km", "7 - 10km", "More than 10km" };
            foreach (string itm in items)
                if (!db.SchoolDistances.Any(sd => sd.Title == itm))
                {
                    db.SchoolDistances.Add(new SchoolDistance() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            items = new string[] { "Unknown", "Non-Working", "Cultivator", "Self Employed in Agriculture", "Beedi Maker",
                                   "NREGA Worker", "Other Casual Labor (Coolie)", "Cattle/Animal Rearing", "Weaver", "Handicraftsman", "Small business owner",
                                   "Student", "Riskshaw Puller", "Housewife", "Factory Worker", "Helper-Weaving activity" };

            foreach (string itm in items)
                if (!db.Occupations.Any(ao => ao.Title == itm))
                {
                    db.Occupations.Add(new Occupation() { Title = itm });
                    needSaving = true;
                }
            if (!db.Occupations.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.Occupations.Add(new Occupation() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            for (byte i = 1; i < 6; i++)
                if (!db.SchoolDaysPerWeek.Any(ao => ao.Id == i))
                {
                    db.SchoolDaysPerWeek.Add(new SchoolDayPerWeek() { Id = i, Title = ""+i });
                    needSaving = true;
                }
            if(needSaving)
            {
                db.SaveChanges();
                needSaving = false;
            }
            //-----------------------------------------------------------------
            items = GetIndianDistricts();
            for (int i = 0; i < items.Length; i += 4)
            {
                string abbr = items[i].ToLower(), name = items[i + 1], stabbr = items[i + 2].ToLower(), cid = items[i + 3].ToLower();
                State st = db.States.Where(x => x.CountryId == cid && x.Abbr == stabbr).FirstOrDefault();
                if (st != null)
                {
                    if (!db.Districts.Any(d => d.StateId == st.Id && (d.Abbr == abbr || d.Name == name)))
                    {
                        db.Districts.Add(new District() { Abbr = abbr, Name = name, StateId = st.Id });
                        needSaving = true;
                        //db.SaveChanges();
                    }
                }
            }
            //-----------------------------------------------------------------
            items = new string[] { "Spiritual Healer / Tantrik", "Homoepathic / Ayurvedic Doctor", "RMP", "Primary Health Centre (PHC) / Govt Doctor",
                                   "Pvt Clinic / MBBS", "Hospital" };
            foreach (string itm in items)
                if (!db.HcProviderTypes.Any(hp => hp.Title == itm))
                {
                    db.HcProviderTypes.Add(new HcProviderType() { Title = itm });
                    needSaving = true;
                }
            if (!db.HcProviderTypes.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.HcProviderTypes.Add(new HcProviderType() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Fever", "Cough", "Diarrehea", "Joint pain", "Fatigue", "Wound", "Skin rash or lesion", "Malaria", "Tuberculosis",
                                   "Animal bite", "Dehydration", "Headache", "Infection", "Gynecological problems", "Tumor/growth" };
            foreach (string itm in items)
                if (!db.HealthIssueTypes.Any(hi => hi.Title == itm))
                {
                    db.HealthIssueTypes.Add(new HealthIssueType() { Title = itm });
                    needSaving = true;
                }
            if (!db.HealthIssueTypes.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.HealthIssueTypes.Add(new HealthIssueType() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Spiritual Healer / Tantrik", "Homoepathic / Ayurvedic Doctor", "RMP", "Primary Health Centre (PHC) / Govt Doctor",
                                   "Pvt Clinic / MBBS", "Hospital" };
            foreach (string itm in items)
                if (!db.MedSourceTypes.Any(ms => ms.Title == itm))
                {
                    db.MedSourceTypes.Add(new MedSourceType() { Title = itm });
                    needSaving = true;
                }
            if (!db.MedSourceTypes.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.MedSourceTypes.Add(new MedSourceType() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Yellow Ration Card", "Red Ration Card", "Blue Ration Card", "Health Card", "Voter ID Card", "Weaver's Card" };
            foreach (string itm in items)
                if (!db.GovCardTypes.Any(gc => gc.Title == itm))
                {
                    db.GovCardTypes.Add(new GovCardType() { Title = itm });
                    needSaving = true;
                }
            if (!db.GovCardTypes.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.GovCardTypes.Add(new GovCardType() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Housing (Indira Awaas Yojana)", "Finance/SHG", "Employment/training", "Childcare/ICDS (Anaganwadi)/Mid-day Meal",
                                   "100 days Work Guarantee (NREGA)", "Ration Shop (PDS)", "Aadhar/Voter ID Card", "Subsidized Yarn or Loom (Weaver's Card)",
                                   "Health Insurance (RSBY)" };

            foreach (string itm in items)
                if (!db.GovServiceTypes.Any(gs => gs.Title == itm))
                {
                    db.GovServiceTypes.Add(new GovServiceType() { Title = itm });
                    needSaving = true;
                }
            if (!db.GovServiceTypes.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.GovServiceTypes.Add(new GovServiceType() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "1", "2 - 3", "4 - 5", "> 5" };
            foreach (string itm in items)
                if (!db.NumberOfRoomsTypes.Any(nx => nx.Title == itm))
                {
                    db.NumberOfRoomsTypes.Add(new NumberOfRoomsType() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            items = new string[] { "Thatch/Mud", "Tiles", "Stones", "Cement" };
            foreach (string itm in items)
                if (!db.WallMaterialTypes.Any(wx => wx.Title == itm))
                {
                    db.WallMaterialTypes.Add(new WallMaterialType() { Title = itm });
                    needSaving = true;
                }
            if (!db.WallMaterialTypes.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.WallMaterialTypes.Add(new WallMaterialType() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Thatch/Mud", "Tiles", "Stones", "Cement" };
            foreach (string itm in items)
                if (!db.RoofMaterialTypes.Any(wx => wx.Title == itm))
                {
                    db.RoofMaterialTypes.Add(new RoofMaterialType() { Title = itm });
                    needSaving = true;
                }
            if (!db.RoofMaterialTypes.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.RoofMaterialTypes.Add(new RoofMaterialType() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Public Well/Tap", "Private Tap", "Private Pump", "Borewell" };
            foreach (string itm in items)
                if (!db.WaterSourceTypes.Any(wx => wx.Title == itm))
                {
                    db.WaterSourceTypes.Add(new WaterSourceType() { Title = itm });
                    needSaving = true;
                }
            if (!db.WaterSourceTypes.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.WaterSourceTypes.Add(new WaterSourceType() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Open", "Pit", "Bricks", "Flush" };
            foreach (string itm in items)
                if (!db.ToiletTypes.Any(wx => wx.Title == itm))
                {
                    db.ToiletTypes.Add(new ToiletType() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            items = new string[] { "Firewood", "Coal", "LPG", "Electricity", "Kerosene" };
            foreach (string itm in items)
                if (!db.CookingEnergyTypes.Any(wx => wx.Title == itm))
                {
                    db.CookingEnergyTypes.Add(new CookingEnergyType() { Title = itm });
                    needSaving = true;
                }
            if (!db.CookingEnergyTypes.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.CookingEnergyTypes.Add(new CookingEnergyType() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            if (!db.HouseQualityTypes.Any(g => g.Title == "Unknown" || g.Id == 0))
            {
                db.HouseQualityTypes.Add(new HouseQualityType() { Id = 0, Title = "Unknown" });
                needSaving = true;
            }
            /*
            if (!db.HouseQualityTypes.Any(g => g.Title == "Pucca" || g.Id == (byte)'p'))
            {
                db.HouseQualityTypes.Add(new HouseQualityType() { Id = (byte)'p', Title = "Pucca" });
                needSaving = true;
            }
            if (!db.HouseQualityTypes.Any(g => g.Title == "Semi-pucca" || g.Id == (byte)'s'))
            {
                db.HouseQualityTypes.Add(new HouseQualityType() { Id = (byte)'s', Title = "Semi-pucca" });
                needSaving = true;
            }
            if (!db.HouseQualityTypes.Any(g => g.Title == "Kacha" || g.Id == (byte)'k'))
            {
                db.HouseQualityTypes.Add(new HouseQualityType() { Id = (byte)'k', Title = "Kacha" });
                needSaving = true;
            }
            */
            //-----------------------------------------------------------------
            items = new string[] { "Unknown", "Self owned", "Rented", "Religious grant", "Government housing" };
            foreach (string itm in items)
                if (!db.HouseOwnershipTypes.Any(ot => ot.Title == itm))
                {
                    db.HouseOwnershipTypes.Add(new HouseOwnershipType() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            items = new string[] { "Unknown", "0 - 15 minutes", "15 - 30 minutes", "30 - 60 minutes", "More than 1 hour" };
            foreach (string itm in items)
                if (!db.WaterSourceDistanceTypes.Any(wd => wd.Title == itm))
                {
                    db.WaterSourceDistanceTypes.Add(new WaterSourceDistanceType() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            items = new string[] { "No loan", "Food", "Medical expense", "School fee", "Asset purchase/maintenance", "Housing",
                                    "Agricultural purpose" };
            foreach (string itm in items)
                if (!db.LoanPurposeTypes.Any(wd => wd.Title == itm))
                {
                    db.LoanPurposeTypes.Add(new LoanPurposeType() { Title = itm });
                    needSaving = true;
                }
            if (!db.LoanPurposeTypes.Any(x => x.Title == "Other" || x.Id == 255))
            {
                db.LoanPurposeTypes.Add(new LoanPurposeType() { Id = 255, Title = "Other" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "No savings", "Bank Account", "Post Office Account", "SHG", "Savings in the household", "Government bonds/Certificates",
                                    "Chit funds" };
            foreach (string itm in items)
                if (!db.SavingsTypes.Any(wd => wd.Title == itm))
                {
                    db.SavingsTypes.Add(new SavingsType() { Title = itm });
                    needSaving = true;
                }
            if (!db.SavingsTypes.Any(x => x.Title == "Others" || x.Id == 255))
            {
                db.SavingsTypes.Add(new SavingsType() { Id = 255, Title = "Others" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            /*
            items = new string[] { "Unknown" };
            foreach (string itm in items)
                if (!db.WorkDaysPerMonthTypes.Any(wd => wd.Title == itm))
                {
                    db.WorkDaysPerMonthTypes.Add(new WorkDaysPerMonthType() { Title = itm });
                    needSaving = true;
                }
            */
            //-----------------------------------------------------------------
            items = new string[] { "Ragi/Bajra", "Rice", "Wheat", "Coarse Millets" };
            foreach (string itm in items)
                if (!db.GrainTypes.Any(wd => wd.Title == itm))
                {
                    db.GrainTypes.Add(new GrainType() { Title = itm });
                    needSaving = true;
                }
            if (!db.GrainTypes.Any(x => x.Title == "Others" || x.Id == 255))
            {
                db.GrainTypes.Add(new GrainType() { Id = 255, Title = "Others" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Chana Dal", "Moong Dal", "Arhar Dal", "Soya Beans", "Masoor Dal", "Black Eyed Dal" };
            foreach (string itm in items)
                if (!db.PulseTypes.Any(wd => wd.Title == itm))
                {
                    db.PulseTypes.Add(new PulseType() { Title = itm });
                    needSaving = true;
                }
            if (!db.PulseTypes.Any(x => x.Title == "Others" || x.Id == 255))
            {
                db.PulseTypes.Add(new PulseType() { Id = 255, Title = "Others" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Tubers (Potato, Sweet potato, Yam, Onion)", "Green leafy vegetables (Spinach, Meethi, Saag)",
                                    "Root vegetables (Radish, Carrot, Tapioca)", "Tomato", "Jackfruit", "Beans" };
            foreach (string itm in items)
                if (!db.VegetableTypes.Any(wd => wd.Title == itm))
                {
                    db.VegetableTypes.Add(new VegetableType() { Title = itm });
                    needSaving = true;
                }
            if (!db.VegetableTypes.Any(x => x.Title == "Others" || x.Id == 255))
            {
                db.VegetableTypes.Add(new VegetableType() { Id = 255, Title = "Others" });
                needSaving = true;
            }
            //-----------------------------------------------------------------
            items = new string[] { "Unknown", "Mostly (more than 5 times per month)", "Often (3-4 times per month)",
                                   "Sometimes (2-3 times per month)", "Rarely", "Never (Don't consume non-veg)" };
            foreach (string itm in items)
                if (!db.AvgNonVegPerMTypes.Any(x => x.Title == itm))
                {
                    db.AvgNonVegPerMTypes.Add(new AvgNonVegPerMType() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            items = new string[] { "Unknown", "Mostly", "Often", "Sometimes", "Rarely", "Never" };
            foreach (string itm in items)
                if (!db.PKGPerMTypes.Any(x => x.Title == itm))
                {
                    db.PKGPerMTypes.Add(new PKGPerMType() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------
            items = new string[] { "School availability", "Can't afford school", "Works for you", "Works for  someone else", "Attended school before",
                                    "Not interested in school", "Not old enough to attend" };
            foreach (string itm in items)
                if (!db.WhyNotInSchoolTypes.Any(wx => wx.Title == itm))
                {
                    db.WhyNotInSchoolTypes.Add(new WhyNotInSchoolType() { Title = itm });
                    needSaving = true;
                }
            //-----------------------------------------------------------------

            if(needSaving)
                db.SaveChanges();

            return View();
        }