using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Diplom_O.DataBase { public class TypeStaj { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public string Name { get; set; } public List CorrStajy { get; set; } public List RabotnikTypeStajy { get; set; } } public static partial class FuncDB { public static void TypeStajCheckValid(TypeStaj obj) { try { if (obj == null) throw new Exception("Ошибка инициализации стажа."); if (string.IsNullOrEmpty(obj.Name)) throw new Exception("Пустой стаж."); } catch { throw; } } public static TypeStaj TypeStajGetById(int id) { try { using (var db = new MainDB()) { var res = from a in db.TypeStajy where a.Id == id select a; try { return res.Single(); } catch { return null; } } } catch { throw; } } public static TypeStaj TypeStajGetByName(string name) { try { using (var db = new MainDB()) { var chkTypeStaj = from a in db.TypeStajy where a.Name == name select a; try { return chkTypeStaj.Single(); } catch { return null; } } } catch { throw; } } public static void TypeStajAdd(TypeStaj obj) { try { TypeStajCheckValid(obj); if (TypeStajGetByName(obj.Name) != null) throw new Exception("Тип стажа существует."); using (var db = new MainDB()) { db.TypeStajy.Add(obj); db.SaveChanges(); } } catch { throw; } } public static void TypeStajChange(TypeStaj obj) { try { TypeStajCheckValid(obj); var localObjById = TypeStajGetById(obj.Id); var localObjByName = TypeStajGetByName(obj.Name); if (localObjById == null) throw new Exception("Тип стажа не существует."); if (localObjByName != null && localObjByName != localObjById) throw new Exception("Тип стажа существует."); using (var db = new MainDB()) { db.TypeStajy.Update(obj); db.SaveChanges(); } } catch { throw; } } public static void TypeStajDelete(TypeStaj obj) { try { if (obj == null) return; var localObj = TypeStajGetById(obj.Id); if (localObj == null) throw new Exception("Тип стажа не существует."); if (RabotnikTypeStajListByTypeStaj(localObj.Id).Length > 0) throw new Exception("Тип стажа используется."); using (var db = new MainDB()) { db.TypeStajy.Remove(localObj); db.SaveChanges(); } } catch { throw; } } public static TypeStaj[] TypeStajList(int[] filter = null) { try { using (var db = new MainDB()) { var res = ( from a in db.TypeStajy where filter == null || filter.Contains(a.Id) select a ).ToList(); return res.ToArray(); } } catch { throw; } } public static string[] TypeStajListString(int[] filter = null) { try { using (var db = new MainDB()) { var res = ( from a in db.TypeStajy where filter == null || filter.Contains(a.Id) select a.Name ).ToList(); res.Remove("Общий"); return res.ToArray(); } } catch { throw; } } } }