Exemple #1
0
 public LinqEngine(DbModel dbModel)
 {
     _dbModel = dbModel;
       _translator = new ExpressionTranslator(dbModel);
       _optimizer = new ExpressionOptimizer();
       _specialExpressionTranslator = new SpecialExpressionTranslator();
 }
Exemple #2
0
 public EntityApp Build(DbFirstConfig config)
 {
     _config = config;
       _app = new EntityApp();
       var log = _app.ActivationLog;
       _dbSettings = new DbSettings(_config.Driver, DbOptions.Default, _config.ConnectionString);
       _dbSettings.SetSchemas(_config.Schemas);
       var modelLoader = _config.Driver.CreateDbModelLoader(_dbSettings, log);
       _dbModel = modelLoader.LoadModel();
       Util.Check(_dbModel.Tables.Count() > 0, "No tables found in the database. Code generation aborted.");
       // Prepare type generator
       _tempNamespace = "_dummy_" + _callCount++; // artificial unique namespace for dummy interface types
       // Construct model setup and model
       GenerateModulesAndAreas();
       _entityModel = new EntityModel(_app);
       EntityModelBuilder.SetModel(_app, _entityModel);
       _entityModel.ClassesAssembly = new EntityClassesAssembly();
       //generate entities and members
       GenerateEntities();
       SetupPrimaryKeys();
       GenerateReferenceMembers();
       CreateIndexes();
       SetupKeyMembers();
       return _app;
 }
 public static Employee Employee(string id)
 {
     using (var context = new DbModel<Employee>())
     {
         return context.Get(id);
     }
 }
Exemple #4
0
        public void AddDbModelChanges(DbUpgradeInfo upgradeInfo, MemoryLog log)
        {
            _upgradeInfo = upgradeInfo;
              _newModel = upgradeInfo.NewDbModel;
              _oldModel = upgradeInfo.OldDbModel;
              _log = log;
              _options = _upgradeInfo.Settings.UpgradeOptions;
              var driver = _newModel.Driver;
              _useRefIntegrity = driver.Supports(DbFeatures.ReferentialConstraints) && _newModel.Config.Options.IsSet(DbOptions.UseRefIntegrity) ;
              _compareTables = _options.IsSet(DbUpgradeOptions.UpdateTables);
              _compareIndexes = _options.IsSet(DbUpgradeOptions.UpdateIndexes);
              _compareViews = driver.Supports(DbFeatures.Views) && _options.IsSet(DbUpgradeOptions.UpdateViews);
              var usesStoredProcs = driver.Supports(DbFeatures.StoredProcedures) && _newModel.Config.Options.IsSet(DbOptions.UseStoredProcs);
              _compareStoredProcs = usesStoredProcs && _options.IsSet(DbUpgradeOptions.UpdateStoredProcs);
              _dropUnknown = _options.IsSet(DbUpgradeOptions.DropUnknownObjects);
              _supportsSchemas = driver.Supports(DbFeatures.Schemas);
              _supportsOrderInIndexes = driver.Supports(DbFeatures.OrderedColumnsInIndexes);

              // Nullify all obj.Peer fields to make sure we drop references to old model - mostly convenience in debugging
              // to allow multiple entry into this method in debugger
              _oldModel.ResetPeerRefs();
              MatchObjectsWithPeers();

              //new stuff
              BuildChangeList();

              // Do not do it here, refs to old objects might be need by Sql generators; we will reset refs after completing update
              // _newModel.ResetPeerRefs()
        }
 public static async Task<string> DeleteEmployee(string id)
 {
     using (var context = new DbModel<Employee>())
     {
         return await context.Remove(id);
     }
 }
 public static Dependent Dependent(string empid, string id)
 {
     using (var context = new DbModel<Employee>())
     {
         var emp = context.Get(empid);
         if (emp == null) return null;
         return emp.Dependents.Where(x => x.id == id).FirstOrDefault();
     }
 }
 public static async Task<Employee> AddEmployee(Employee employee)
 {
     using (var context = new DbModel<Employee>())
     {
         if (employee.Dependents == null)
             employee.Dependents = new List<Dependent>();
         return await context.Add(employee);
     }
 }
 public static async Task<Benefits> AddDiscount(BenefitsDiscount benefitsDiscount)
 {
     using (var context = new DbModel<Benefits>())
     {
         var benef = context.First();
         benef.Discounts.Add(benefitsDiscount);
         return await context.Update(benef);
     }
 }
Exemple #9
0
        public bool VersionsChanged; //true if detected any version changes

        #endregion Fields

        #region Constructors

        public DbUpgradeInfo(DbSettings settings, DbModel newModel)
        {
            Settings = settings;
              NewDbModel = newModel;
              var serverType = NewDbModel.Driver.ServerType;
              Id = Guid.NewGuid();
              Method = DbUpgradeMethod.Auto; //might be changed by update tool app
              UserName = "******";
              Status = UpgradeStatus.None;
        }
Exemple #10
0
 public TranslationContext(TranslationContext source)
 {
     this.DbModel = source.DbModel;
       this.Command = source.Command;
       this.CallStack = source.CallStack;
       this.ExternalValues = source.ExternalValues;
       this.MetaTables = source.MetaTables;
       this.SelectExpressions = source.SelectExpressions;
       this.LambdaParameters = source.LambdaParameters;
       this._currentScopeIndex = source._currentScopeIndex;
 }
 public static async Task<Benefits> UpdateCosts(BenefitsCost benefitsCost)
 {
     using (var context = new DbModel<Benefits>())
     {
         var benef = context.First();
         benef.Cost.Employee = benefitsCost.Employee;
         benef.Cost.Dependent = benefitsCost.Dependent;
         benef.Cost.Description = benefitsCost.Description;
         return await context.Update(benef);
     }
 }
 public static async Task<Benefits> DeleteDiscount(string id)
 {
     using (var context = new DbModel<Benefits>())
     {
         var benef = context.First();
         var bd = benef.Discounts.Where(x => x.id == id).FirstOrDefault();
         if (bd == null)
             return null;
         benef.Discounts.Remove(bd);
         return await context.Update(benef);
     }
 }
 public static async Task<Employee> DeleteDependent(string empid, string id)
 {
     using (var context = new DbModel<Employee>())
     {
         var emp = context.Get(empid);
         if (emp == null) return null;
         var dep = emp.Dependents.Where(x => x.id == id).FirstOrDefault();
         if (dep == null) return null;
         emp.Dependents.Remove(dep);
         return await context.Update(emp);
     }
 }
Exemple #14
0
 public TranslationContext(DbModel dbModel, LinqCommand command)
 {
     DbModel = dbModel;
       Command = command;
       CallStack = new Stack<MethodInfo>();
       SelectExpressions = new List<SelectExpression>();
       _currentScopeIndex = SelectExpressions.Count;
       SelectExpressions.Add(new SelectExpression());
       ExternalValues = new List<ExternalValueExpression>();
       MetaTables = new List<MetaTableExpression>();
       LambdaParameters = new Dictionary<string, Expression>();
 }
 public static async Task<Employee> AddDependent(string empid, Dependent dependent)
 {
     using (var context = new DbModel<Employee>())
     {
         var emp = context.Get(empid);
         if (emp == null)
             return null;
         if (emp.Dependents == null)
             emp.Dependents = new List<Dependent>();
         emp.Dependents.Add(dependent);
         return await context.Update(emp);
     }
 }
 public static async Task<Benefits> UpdateDiscount(string id, BenefitsDiscount benefitsDiscount)
 {
     using (var context = new DbModel<Benefits>())
     {
         var benef = context.First();
         var bd = benef.Discounts.Where( x => x.id == id).FirstOrDefault();
         if (bd == null)
             return null;
         bd.Percentage = benefitsDiscount.Percentage;
         bd.Predicate = benefitsDiscount.Predicate;
         bd.Description = benefitsDiscount.Description;
         return await context.Update(benef);
     }
 }
 public static async Task<Employee> UpdateEmployee(string id, Employee employee)
 {
     using (var context = new DbModel<Employee>())
     {
         var emp = context.Get(id);
         if (emp == null)
             return null;
         emp.Name = employee.Name;
         emp.Email = employee.Email;
         emp.Age = employee.Age;
         emp.PaycheckAmount = employee.PaycheckAmount;
         emp.PaychecksPerYear = employee.PaychecksPerYear;
         emp.HireDate = employee.HireDate;
         return await context.Update(emp);
     }
 }
 /// <summary>
 /// Add Demo data to the database (10 random employee names will be added)
 /// </summary>
 /// <param name="count">The count of employees to add (default = 10)</param>
 /// <returns>Returns a list of names for those employees added</returns>        
 public async Task<IHttpActionResult> Get(int count = 10)
 {
     try
     {
         var employees = new List<string>();
         using (var context = new DbModel<Employee>())
         {
             for (int i = 0; i < count; i++)
             {
                 string name = RandomName;
                 int age = rnd.Next(28, 45);
                 employees.Add(name);
                 var newEmployee = new Employee
                 {
                     Name = name,
                     Email = name.Replace(' ', '.') + "@test.us",
                     Age = age,
                     PaycheckAmount = 2000.00,
                     PaychecksPerYear = 26,
                     HireDate = DateTime.Now.AddDays(-rnd.Next(500, (age - 22) * 300)),
                     Dependents = new List<Dependent>()
                 };
                 // Add some dependents
                 for (int j = 0; j < rnd.Next(0, 4); j++)
                 {
                     var dependent = new Dependent
                     {
                         Name = RandomName,
                         Age = rnd.Next(age++, age + 10)
                     };
                     newEmployee.Dependents.Add(dependent);
                 }
                 await context.Add(newEmployee);
             }
         }
         return Ok(employees);
     }
     catch (Exception e)
     {
         logger.Error(e);
         return InternalServerError(e);
     }
 }
Exemple #19
0
 public DbModel Build()
 {
     // create model
       _dbModel = new DbModel(_entityModel.App, _config);
       _dbSqlBuilder = _driver.CreateDbSqlBuilder(_dbModel);
       _driver.OnDbModelConstructing(_dbModel);
       BuildTables();
       CreateTableKeys();
       SetupOrderBy();
       //ref constraints are created in a separate loop, after creating PKs
       BuildRefConstraints();
       CheckObjectNames();
       CompileViews();
       BuildCrudCommands();
       BuildSequences();
       _driver.OnDbModelConstructed(_dbModel);
       CheckErrors();
       return _dbModel;
 }
 public static Benefits Benefits(bool bypassCache)
 {
     var response = new Benefits();
     var memCache = MemoryCache.Default.Get(Constants.Cache.BENEFITS);
     if ((bypassCache) || (memCache == null))
     {
         using (var context = new DbModel<Benefits>())
         {
             response = context.First();
         }
         var policy = new CacheItemPolicy { SlidingExpiration = TimeSpan.FromHours(1) };
         MemoryCache.Default.Add(Constants.Cache.BENEFITS, response, policy);
     }
     else
     {
         response = (Benefits)memCache;
     }
     return response;
 }
        static public async Task Initialize()
        {
            using (var context = new DbModel<Employee>())
            {
                await context.Initialize();
            }

            using (var context = new DbModel<Benefits>())
            {
                await context.Initialize();
                await context.Update(
                    new Benefits
                    {
                        id = "1",
                        Cost = initCost,
                        Discounts = initDiscount
                    }
                );
            }
        }
        private void _ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            splSelectedTest.Children.Clear();
            selectedTest = _ListView.SelectedItem as Test;
            if (selectedTest != null)
            {
                using (var db = new DbModel())
                {
                    int i = 0;
                    //var query = from t in db.Tests
                    //            join q in db.Questions on t.ID equals q.TestFk
                    //            join a in db.Answers on q.ID equals a.QuestionFk
                    //            where t.ID == test.ID
                    //            select new { QuestionText = q.Name, QuestionType = q.QuestionType, Answer = a.Text };
                    foreach (var item in db.Questions.ToList())
                    {
                        if (item.TestFk == selectedTest.ID)
                        {
                            i++;
                            TextBlock txtBlock = new TextBlock();
                            txtBlock.Text = "Fråga " + i;
                            splSelectedTest.Children.Add(txtBlock);
                            TextBlock txt = new TextBlock();
                            txt.Text = item.Name;
                            if (!String.IsNullOrEmpty(item.AppData))
                            {
                                Image       imgQuestion = new Image();
                                string      imgPath     = item.AppData;
                                Uri         imgUri      = new Uri(imgPath);
                                BitmapImage imgBitMap   = new BitmapImage(imgUri);
                                imgQuestion.Source    = imgBitMap;
                                imgQuestion.MaxHeight = 200;
                                imgQuestion.MaxWidth  = 200;
                                splSelectedTest.Children.Add(imgQuestion);
                            }
                            splSelectedTest.Children.Add(txt);

                            foreach (var a in db.Answers.ToList())
                            {
                                if (a.QuestionFk == item.ID)
                                {
                                    switch (item.QuestionType)
                                    {
                                    case "envalsfråga":
                                        RadioButton ans = new RadioButton();
                                        ans.Content = a.Text;
                                        splSelectedTest.Children.Add(ans);
                                        break;

                                    case "Flervalsfråga":
                                        CheckBox ans2 = new CheckBox();
                                        ans2.Content = a.Text;
                                        splSelectedTest.Children.Add(ans2);
                                        break;

                                    case "rangordning":
                                        TextBlock ans3 = new TextBlock();
                                        ans3.Text = a.Text;
                                        splSelectedTest.Children.Add(ans3);
                                        break;

                                    default:
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    Button     sendbtn            = new Button();
                    Button     sendBackbtn        = new Button();
                    StackPanel splSendTestControl = new StackPanel();
                    splSendTestControl.Orientation = Orientation.Horizontal;
                    sendbtn.Content     = "Skicka till studenter";
                    sendBackbtn.Content = "Skicka till lärare";
                    splSendTestControl.Children.Add(sendbtn);
                    splSendTestControl.Children.Add(sendBackbtn);
                    splSelectedTest.Children.Add(splSendTestControl);
                    sendbtn.Click     += Sendbtn_Click;
                    sendBackbtn.Click += SendBackbtn_Click;
                }
            }
        }
Exemple #23
0
 public PgDbSqlBuilder(DbModel model) : base(model)
 {
 }
Exemple #24
0
 public void Dispose()
 {
     this.ConnectionString = null;
     this.DbModel          = null;
 }
Exemple #25
0
 private DbTableInfo FindTable(DbModel dbModel, string schema, string tableName)
 {
     return(dbModel.GetTable(schema, tableName));
 }
Exemple #26
0
 public TurretRepository(DbModel context)
     : base(context)
 {
 }
Exemple #27
0
        /// <inheritdoc />
        public void Apply(EntityType item, DbModel model)
        {
            var indexInfos = new List <IndexInfo>();

            foreach (var property in item.Properties)
            {
                foreach (var metadataProperty in property.MetadataProperties)
                {
                    if (!(metadataProperty.Value is IndexAnnotation annotation))
                    {
                        continue;
                    }

                    foreach (var index in annotation.Indexes)
                    {
                        var info = index.Name != null?indexInfos.FirstOrDefault(e => e.Name == index.Name) : null;

                        if (info == null)
                        {
                            info = new IndexInfo {
                                Name = index.Name
                            };
                            indexInfos.Add(info);
                        }
                        else
                        {
                            var other = info.Entries[0].Index;
                            if (index.IsUnique != other.IsUnique || index.IsClustered != other.IsClustered)
                            {
                                throw new Exception("Invalid index configuration.");
                            }
                        }

                        info.Entries.Add(new IndexEntry {
                            Column = property, Annotation = metadataProperty, Index = index
                        });
                    }
                }
            }

            if (indexInfos.Count == 0)
            {
                return;
            }

            foreach (var indexInfo in indexInfos)
            {
                var columns = indexInfo.Entries.OrderBy(e => e.Index.Order).Select(e => e.Column.Name).ToList();

                if (indexInfo.Name != null && indexInfo.Name != IndexOperation.BuildDefaultName(columns))
                {
                    continue;
                }

                bool unique = indexInfo.Entries[0].Index.IsUnique;

                string name = $"{(unique ? "UX" : "IX")}_{string.Join("_", columns.Select(column => column.Replace("_", string.Empty)))}";

                if (name.Length > 128)
                {
                    name = name.Substring(0, 128);
                }
                if (indexInfo.Name == name)
                {
                    continue;
                }

                foreach (var entry in indexInfo.Entries)
                {
                    var index = new IndexAttribute(name);
                    if (entry.Index.Order >= 0)
                    {
                        index.Order = entry.Index.Order;
                    }
                    if (entry.Index.IsUniqueConfigured)
                    {
                        index.IsUnique = entry.Index.IsUnique;
                    }
                    if (entry.Index.IsClusteredConfigured)
                    {
                        index.IsClustered = entry.Index.IsClustered;
                    }

                    entry.Index    = index;
                    entry.Modified = true;
                }
            }

            foreach (var indexInfo in indexInfos.SelectMany(ii => ii.Entries).GroupBy(e => e.Annotation))
            {
                if (indexInfo.Any(e => e.Modified))
                {
                    indexInfo.Key.Value = new IndexAnnotation(indexInfo.Select(e => e.Index));
                }
            }
        }
Exemple #28
0
 public LinqSqlProvider(DbModel dbModel)
 {
     DbModel = dbModel;
     Driver = dbModel.Driver;
 }
 public SQLiteLinqSqlProvider(DbModel dbModel)  : base(dbModel)
 {
 }
 public CourseController(DbModel db)
 {
     this.db = db;
 }
 protected EdmType GetStorePrimitiveType(DbModel model, PrimitiveTypeKind typeKind)
 {
     return(model.ProviderManifest.GetStoreType(TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(typeKind))).EdmType);
 }
 public abstract IConfiguration Discover(EdmProperty property, DbModel model);
 public GroupFamilyQuery(DbModel context)
 {
     model = context;
 }
 public bool Serialize(DbModel edmModel, XmlWriter xmlWriter)
 {
     return(_serializer.Serialize(edmModel.DatabaseMapping, xmlWriter));
 }
Exemple #35
0
 public UserMasterBAL()
 {
     db = new DbModel();
 }
        public void Apply(EdmModel item, DbModel model)
        {
            // fn_GetLookUpCode
            var valueParameter1 = FunctionParameter.Create("CodeName", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            var valueParameter2 = FunctionParameter.Create("Id", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int16), ParameterMode.In);
            var valueParameter3 = FunctionParameter.Create("culture", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            var returnValue     = FunctionParameter.Create("result", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.ReturnValue);
            var function        = this.CreateAndAddFunction(item, "fn_GetLookUpCode", new[] { valueParameter1, valueParameter2, valueParameter3 }, new[] { returnValue });

            // fn_GetLookUpUserCode
            valueParameter1 = FunctionParameter.Create("CodeName", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            valueParameter2 = FunctionParameter.Create("Id", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int16), ParameterMode.In);
            valueParameter3 = FunctionParameter.Create("culture", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            returnValue     = FunctionParameter.Create("result", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.ReturnValue);
            function        = this.CreateAndAddFunction(item, "fn_GetLookUpUserCode", new[] { valueParameter1, valueParameter2, valueParameter3 }, new[] { returnValue });
            // fn_GetSysCodeId
            valueParameter1 = FunctionParameter.Create("CodeName", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            valueParameter2 = FunctionParameter.Create("CodeId", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int16), ParameterMode.In);
            returnValue     = FunctionParameter.Create("result", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int16), ParameterMode.ReturnValue);
            function        = this.CreateAndAddFunction(item, "fn_GetSysCodeId", new[] { valueParameter1, valueParameter2 }, new[] { returnValue });
            // fn_GetAttachments
            valueParameter1 = FunctionParameter.Create("Source", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            valueParameter2 = FunctionParameter.Create("SourceId", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int32), ParameterMode.In);
            returnValue     = FunctionParameter.Create("result", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int32), ParameterMode.ReturnValue);
            function        = this.CreateAndAddFunction(item, "fn_GetAttachments", new[] { valueParameter1, valueParameter2 }, new[] { returnValue });
            // fn_ForceUpload
            valueParameter1 = FunctionParameter.Create("Source", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            valueParameter2 = FunctionParameter.Create("SourceId", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int32), ParameterMode.In);
            returnValue     = FunctionParameter.Create("result", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int32), ParameterMode.ReturnValue);
            function        = this.CreateAndAddFunction(item, "fn_ForceUpload", new[] { valueParameter1, valueParameter2 }, new[] { returnValue });

            // fn_GetDocsCount
            valueParameter1 = FunctionParameter.Create("CompanyId", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int32), ParameterMode.In);
            valueParameter2 = FunctionParameter.Create("EmpId", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int32), ParameterMode.In);
            valueParameter3 = FunctionParameter.Create("JobId", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int32), ParameterMode.In);
            returnValue     = FunctionParameter.Create("result", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.ReturnValue);
            function        = this.CreateAndAddFunction(item, "fn_GetDocsCount", new[] { valueParameter1, valueParameter2, valueParameter3 }, new[] { returnValue });

            // fn_TrlsName
            valueParameter1 = FunctionParameter.Create("Name", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            valueParameter2 = FunctionParameter.Create("Culture", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            returnValue     = FunctionParameter.Create("result", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.ReturnValue);
            function        = this.CreateAndAddFunction(item, "fn_TrlsName", new[] { valueParameter1, valueParameter2 }, new[] { returnValue });

            // fn_TrlsMsg
            valueParameter1 = FunctionParameter.Create("Name", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            valueParameter2 = FunctionParameter.Create("Culture", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            returnValue     = FunctionParameter.Create("result", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.ReturnValue);
            function        = this.CreateAndAddFunction(item, "fn_TrlsMsg", new[] { valueParameter1, valueParameter2 }, new[] { returnValue });

            // fn_GetEmpStatus
            valueParameter1 = FunctionParameter.Create("EmpId", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int32), ParameterMode.In);
            returnValue     = FunctionParameter.Create("result", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int32), ParameterMode.ReturnValue);
            function        = this.CreateAndAddFunction(item, "fn_GetEmpStatus", new[] { valueParameter1 }, new[] { returnValue });

            // fn_GetCompanyDoc
            valueParameter1 = FunctionParameter.Create("Source", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            valueParameter2 = FunctionParameter.Create("SourceId", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int32), ParameterMode.In);
            valueParameter3 = FunctionParameter.Create("TypeId", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int32), ParameterMode.In);
            returnValue     = FunctionParameter.Create("result", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.ReturnValue);
            function        = this.CreateAndAddFunction(item, "fn_GetCompanyDoc", new[] { valueParameter1, valueParameter2, valueParameter3 }, new[] { returnValue });

            // Format
            valueParameter1 = FunctionParameter.Create("value", this.GetStorePrimitiveType(model, PrimitiveTypeKind.DateTime), ParameterMode.In);
            valueParameter2 = FunctionParameter.Create("format", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            valueParameter3 = FunctionParameter.Create("culture", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            returnValue     = FunctionParameter.Create("result", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.ReturnValue);
            function        = this.CreateAndAddFunction(item, "FORMAT", new[] { valueParameter1, valueParameter2, valueParameter3 }, new[] { returnValue });

            //fn_GetPageId
            valueParameter1 = FunctionParameter.Create("CompanyId", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int32), ParameterMode.In);
            valueParameter2 = FunctionParameter.Create("ObjectName", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            valueParameter3 = FunctionParameter.Create("Version", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int32), ParameterMode.In);
            returnValue     = FunctionParameter.Create("result", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int32), ParameterMode.ReturnValue);
            function        = this.CreateAndAddFunction(item, "fn_GetPageId", new[] { valueParameter1, valueParameter2, valueParameter3 }, new[] { returnValue });
            //fn_GetColumnTitle
            valueParameter1 = FunctionParameter.Create("CompanyId", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int32), ParameterMode.In);
            valueParameter2 = FunctionParameter.Create("culture", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            valueParameter3 = FunctionParameter.Create("ObjectName", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            var valueParameter4 = FunctionParameter.Create("Version", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int32), ParameterMode.In);
            var valueParameter5 = FunctionParameter.Create("ColumnName", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);

            returnValue = FunctionParameter.Create("result", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.ReturnValue);
            function    = this.CreateAndAddFunction(item, "fn_GetColumnTitle", new[] { valueParameter1, valueParameter2, valueParameter3, valueParameter4, valueParameter5 }, new[] { returnValue });

            // fn_GetWorkFlowStatus
            valueParameter1 = FunctionParameter.Create("Source", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            valueParameter2 = FunctionParameter.Create("SourceId", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int32), ParameterMode.In);
            valueParameter3 = FunctionParameter.Create("DocumentId", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int32), ParameterMode.In);
            valueParameter4 = FunctionParameter.Create("culture", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            returnValue     = FunctionParameter.Create("result", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.ReturnValue);
            function        = this.CreateAndAddFunction(item, "fn_GetWorkFlowStatus", new[] { valueParameter1, valueParameter2, valueParameter3, valueParameter4 }, new[] { returnValue });

            // fn_CommaSeperatedNames
            valueParameter1 = FunctionParameter.Create("table", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            valueParameter4 = FunctionParameter.Create("comma", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            valueParameter5 = FunctionParameter.Create("culture", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            returnValue     = FunctionParameter.Create("result", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.ReturnValue);
            function        = this.CreateAndAddFunction(item, "fn_CommaSeperatedNames", new[] { valueParameter1, valueParameter4, valueParameter5 }, new[] { returnValue });

            //fn_GetDoc
            var param1 = FunctionParameter.Create("Source", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            var param2 = FunctionParameter.Create("SourceId", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int32), ParameterMode.In);

            returnValue = FunctionParameter.Create("result", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.ReturnValue);
            function    = this.CreateAndAddFunction(item, "fn_GetDoc", new[] { param1, param2 }, new[] { returnValue });

            //fn_GetDocument
            param1      = FunctionParameter.Create("Source", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            param2      = FunctionParameter.Create("SourceId", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int32), ParameterMode.In);
            returnValue = FunctionParameter.Create("result", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.ReturnValue);
            function    = this.CreateAndAddFunction(item, "fn_GetDocument", new[] { param1, param2 }, new[] { returnValue });

            //fn_GetStramDoc
            var valueparam1 = FunctionParameter.Create("Source", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            var valueparam2 = FunctionParameter.Create("SourceId", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Int32), ParameterMode.In);

            returnValue = FunctionParameter.Create("result", this.GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.ReturnValue);
            function    = this.CreateAndAddFunction(item, "fn_GetStramDoc", new[] { valueparam1, valueparam2 }, new[] { returnValue });

            //// fn_FilterRequestTabs
            //valueParameter1 = FunctionParameter.Create("Tab", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Byte), ParameterMode.In);
            //valueParameter2 = FunctionParameter.Create("ApprovalStatus", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Byte), ParameterMode.In);
            //valueParameter3 = FunctionParameter.Create("Start", this.GetStorePrimitiveType(model, PrimitiveTypeKind.DateTime), ParameterMode.In);
            //valueParameter4 = FunctionParameter.Create("End", this.GetStorePrimitiveType(model, PrimitiveTypeKind.DateTime), ParameterMode.In);
            //returnValue = FunctionParameter.Create("result", this.GetStorePrimitiveType(model, PrimitiveTypeKind.Boolean), ParameterMode.ReturnValue);
            //function = this.CreateAndAddFunction(item, "fn_FilterRequestTabs", new[] { valueParameter1, valueParameter2, valueParameter3, valueParameter4 }, new[] { returnValue });
        }
Exemple #37
0
        public void Apply(EntityContainer item, DbModel model)
        {
            var functionDescriptors  = new FunctionDiscovery(model, _methodClassType).FindFunctions();
            var storeFunctionBuilder = new StoreFunctionBuilder(model, _defaultSchema);

            foreach (var functionDescriptor in functionDescriptors)
            {
                var storeFunctionDefinition = storeFunctionBuilder.Create(functionDescriptor);
                model.StoreModel.AddItem(storeFunctionDefinition);

                if (functionDescriptor.StoreFunctionKind != StoreFunctionKind.ScalarUserDefinedFunction)
                {
                    var functionImportDefinition = CreateFunctionImport(model, functionDescriptor);
                    model.ConceptualModel.Container.AddFunctionImport(functionImportDefinition);

                    List <FunctionImportResultMapping> resultMappings = new List <FunctionImportResultMapping>();
                    if (functionDescriptor.ReturnTypes.All(t => t is EntityType || t is ComplexType))
                    {
                        foreach (EdmType returnType in functionDescriptor.ReturnTypes)
                        {
                            FunctionImportStructuralTypeMapping typeMapping;
                            if (returnType is EntityType)
                            {
                                var entityType = (EntityType)returnType;

                                var returnTypePropertyMappings = new Collection <FunctionImportReturnTypePropertyMapping>();
                                foreach (var propertyMapping in model.GetEntityTypePropertyMappings(entityType).OfType <ScalarPropertyMapping>())
                                {
                                    returnTypePropertyMappings.Add(new FunctionImportReturnTypeScalarPropertyMapping(propertyMapping.Property.Name, propertyMapping.Column.Name));
                                }

                                typeMapping = new FunctionImportEntityTypeMapping(
                                    Enumerable.Empty <EntityType>(),
                                    new[] { entityType },
                                    returnTypePropertyMappings,
                                    Enumerable.Empty <FunctionImportEntityTypeMappingCondition>());
                            }
                            else // ComplexType
                            {
                                var complexType = (ComplexType)returnType;

                                var returnTypePropertyMappings = new Collection <FunctionImportReturnTypePropertyMapping>();
                                foreach (var property in complexType.Properties)
                                {
                                    returnTypePropertyMappings.Add(new FunctionImportReturnTypeScalarPropertyMapping(property.Name, property.Name));
                                }

                                typeMapping = new FunctionImportComplexTypeMapping(complexType, returnTypePropertyMappings);
                            }

                            FunctionImportResultMapping resultMapping = new FunctionImportResultMapping();
                            resultMappings.Add(resultMapping);
                            resultMapping.AddTypeMapping(typeMapping);
                        }
                    }

                    if (functionImportDefinition.IsComposableAttribute)
                    {
                        model.ConceptualToStoreMapping.AddFunctionImportMapping(
                            new FunctionImportMappingComposable(
                                functionImportDefinition,
                                storeFunctionDefinition,
                                resultMappings.FirstOrDefault() ?? new FunctionImportResultMapping(),
                                model.ConceptualToStoreMapping));
                    }
                    else
                    {
                        // HACK: Currently, FunctionImportMappingNonComposable ctor does not support code-first construction because
                        //       it depends on EdmItemCollection being available from StorageMappingItemCollection. Code-first does
                        //       not create a StorageMappingItemCollection and, as a result, this ctor will throw a null reference
                        //       exception if any result mappings are passed to it in code-first context. This must be resolved in
                        //       EF itself. Until then, _only composable functions can support custom named column mappings_. Once
                        //       this issue is resolved in EF then the commented code should replace the current "empty array"
                        //       resultMapping parameter to enable custom mappings for non-composable functions as well:
                        model.ConceptualToStoreMapping.AddFunctionImportMapping(
                            new FunctionImportMappingNonComposable(
                                functionImportDefinition,
                                storeFunctionDefinition,
                                // resultMappings.Any() ? resultMappings.ToArray() : new FunctionImportResultMapping[0],
                                new FunctionImportResultMapping[0],
                                model.ConceptualToStoreMapping));
                    }
                }
            }

            // TODO: model defined functions?
        }
Exemple #38
0
        public void Apply(EdmProperty property, DbModel model)
        {
            var columnName = char.ToLower(property.Name[0]) + property.Name.Substring(1);

            property.Name = columnName;
        }
Exemple #39
0
 public FunctionParameter ToFunctionParameter([NotNull] DbModel model, ParameterMode mode)
 {
     return(FunctionParameter.Create(Name, model.GetStorePrimitiveType(Kind), mode));
 }
Exemple #40
0
 public OracleCrudSqlBuilder(DbModel dbModel) : base(dbModel)
 {
 }
Exemple #41
0
 public MySqlDbSqlBuilder(DbModel dbModel) : base(dbModel)
 {
 }
 public MovieController()
 {
     db = new DbModel();
 }
Exemple #43
0
 public LinqEngine(DbModel dbModel)
 {
     _dbModel     = dbModel;
     _entityModel = _dbModel.EntityModel;
     _translator  = new ExpressionTranslator(dbModel);
 }
Exemple #44
0
 public EntityFrameworkUnitOfWorkFactory(string connectionString, DbModel dbModel)
 {
     this.ConnectionString = connectionString;
     this.DbModel          = dbModel;
 }
Exemple #45
0
 public override Vita.Data.Driver.LinqSqlProvider CreateLinqSqlProvider(DbModel dbModel)
 {
     return new MySqlLinqSqlProvider(dbModel);
 }
Exemple #46
0
 public override DbSqlBuilder CreateDbSqlBuilder(DbModel dbModel)
 {
     return new MySqlDbSqlBuilder(dbModel);
 }
Exemple #47
0
 public abstract LinqSqlProvider CreateLinqSqlProvider(DbModel dbModel);
Exemple #48
0
 protected abstract void ProcessModel(
     DbModel model, string storeModelNamespace, ModelBuilderSettings settings,
     ModelBuilderEngineHostContext hostContext, List <EdmSchemaError> errors);
Exemple #49
0
 public DbTableInfo(DbModel model, string schema, string tableName, EntityInfo entity, DbObjectType objectType = DbObjectType.Table)
     : base(model, schema, objectType, entity)
 {
     TableName = tableName;
       Entity = entity; //might be null
       Kind = EntityKind.Table;
       if (Entity != null)
     Kind = Entity.Kind;
       else if (objectType == DbObjectType.View)
     Kind = EntityKind.View; // when loading from database
       FullName = model.Driver.GetFullName(Schema, tableName);
       base.GlobalName = DbModelHelper.GetGlobalName(Schema, TableName);
       model.AddTable(this);
 }
Exemple #50
0
 // maxParamsCount is 2300 for MS SQL, but we're being a bit cautious here
 public MsLinqSqlBuilder(DbModel dbModel, LinqCommand command) : base(dbModel, command)
 {
     _msDialect = (MsSqlDialect)dbModel.Driver.SqlDialect;
 }
Exemple #51
0
 public SqlCeDbSqlBuilder(DbModel dbModel)
     : base(dbModel)
 {
 }
 public UserRepository(DbModel model)
 {
     this.context = model;
 }
Exemple #53
0
        public override void OnDbModelConstructed(DbModel dbModel)
        {
            foreach (var table in dbModel.Tables) {
            // Names of PK constraints in MySql is 'PRIMARY', cannot be changed
            // PK is always used as clustered index, but we consider clustered indexes as not supported in MySql
            if (table.PrimaryKey != null)
              table.PrimaryKey.Name = "PRIMARY";

            // All foreign keys have a supporting index; if there's no matching index already, it is created automatically.
            foreach(var key in table.Keys) {
              if (key.KeyType.IsSet(KeyType.ForeignKey)) {
            var supportingIndex = DbModelHelper.FindMatchingIndex(key, table.Keys);
            if (supportingIndex == null) //if no supporting index, then mark this key as an index
              key.KeyType |= KeyType.Index;
              }
              //Drop descending flag - see notes at the top of the file
              // MySql supports ordered columns in indexes, but there's no way to get this information
              // when loading index columns from the database - at least I don't know any
              //  so we set all column direction to ASC after construction DbModel
              foreach(var kc in key.KeyColumns)
            kc.Desc = false;
            }
            // auto_increment (identity) columns must be associated with key (PK or index). For auto-inc columns that are NOT PKs we create artificial index
            var autoIncCols = table.Columns.Where(c => c.Flags.IsSet(DbColumnFlags.Identity));
            foreach (var col in autoIncCols) {
              if (col.Flags.IsSet(DbColumnFlags.PrimaryKey))
            continue;
              var ind = new DbKeyInfo(col.ColumnName, col.Table, KeyType.Index); //added automatically to table.Keys list
              ind.KeyColumns.Add(new DbKeyColumnInfo(col));
            }

              }
              // Remove double-quotes from StoredProcedure names - MySqlDriver does not like it
              foreach (var cmd in dbModel.Commands) {
            cmd.FullCommandName = cmd.FullCommandName.Replace("\"", "");
              }
              base.OnDbModelConstructed(dbModel);
        }
Exemple #54
0
        private void CreateDatabase(Database db, DbModel model)
        {
            const string tableTmpl      = "CREATE TABLE [{0}] (\n{1}\n);";
            const string columnTmpl     = "    [{0}] {1} {2}";         // name, type, decl
            const string primaryKeyTmpl = "    [{0}] INTEGER PRIMARY KEY AUTOINCREMENT ";
            const string foreignKeyTmpl = "    FOREIGN KEY ({0}) REFERENCES {1} ({2})";
            const string indexTmpl      = "CREATE INDEX {0} ON {1} ({2});";

            var indicies = new Dictionary <string, Index>();

            foreach (var type in model.StoreModel.EntityTypes)
            {
                var defs = new List <string>();

                // columns
                foreach (var p in type.Properties)
                {
                    var decls = new HashSet <string>();

                    if (!p.Nullable)
                    {
                        decls.Add("NOT NULL");
                    }

                    var annotations = p.MetadataProperties
                                      .Select(x => x.Value)
                                      .OfType <IndexAnnotation>();

                    foreach (var annotation in annotations)
                    {
                        foreach (var attr in annotation.Indexes)
                        {
                            if (attr.IsUnique)
                            {
                                decls.Add("UNIQUE");
                            }

                            if (string.IsNullOrEmpty(attr.Name))
                            {
                                continue;
                            }

                            Index index;
                            if (!indicies.TryGetValue(attr.Name, out index))
                            {
                                index = new Index
                                {
                                    Name    = attr.Name,
                                    Table   = type.Name,
                                    Columns = new List <string>(),
                                };
                                indicies.Add(index.Name, index);
                            }
                            index.Columns.Add(p.Name);
                        }
                    }
                    if (p.Name == "Id")
                    {
                        continue;
                    }
                    defs.Add(string.Format(columnTmpl, p.Name, p.TypeName, string.Join(" ", decls)));
                }

                // primary keys
                if (type.KeyProperties.Any())
                {
                    var keys = type.KeyProperties.Select(x => x.Name);
                    defs.Add(string.Format(primaryKeyTmpl, string.Join(", ", keys)));
                }

                // foreign keys
                foreach (var assoc in model.StoreModel.AssociationTypes)
                {
                    if (assoc.Constraint.ToRole.Name == type.Name)
                    {
                        var thisKeys = assoc.Constraint.ToProperties.Select(x => x.Name);
                        var thatKeys = assoc.Constraint.FromProperties.Select(x => x.Name);
                        defs.Add(string.Format(foreignKeyTmpl,
                                               string.Join(", ", thisKeys),
                                               assoc.Constraint.FromRole.Name,
                                               string.Join(", ", thatKeys)));
                    }
                }

                // create table
                var sql = string.Format(tableTmpl, type.Name, string.Join(",\n", defs));
                db.ExecuteSqlCommand(sql);
            }

            // create index
            foreach (var index in indicies.Values)
            {
                var columns = string.Join(", ", index.Columns);
                var sql     = string.Format(indexTmpl, index.Name, index.Table, columns);
                db.ExecuteSqlCommand(sql);
            }
        }
Exemple #55
0
 public abstract SqlFragment GetSql(DbModel dbModel);
Exemple #56
0
 public QueryFactory(DbModel context)
 {
     model = context;
 }
Exemple #57
0
 public abstract DbSqlBuilder CreateDbSqlBuilder(DbModel dbModel);
Exemple #58
0
 public override SqlFragment GetSql(DbModel dbModel)
 {
     return(new TextSqlFragment(Value));
 }
Exemple #59
0
 public virtual void OnDbModelConstructing(DbModel dbModel)
 {
 }
Exemple #60
0
        private void AddDataToBase()
        {
            List <Answer>     lxAnswer    = AddAnswer();                         //Done
            List <Course>     lxCourse    = AddCourse();                         //Done
            List <Occupation> lxOcc       = AddOccupation();                     //Done
            List <Questions>  lxQuestions = AddQuestion();                       //Done

            List <Student>            lxStudent       = AddStudent();            //Done
            List <StudentAnswer>      lxStudentAnswer = AddStudentAwnser();      //Done
            List <StudentClassCourse> lxSGC           = AddStudentClassCourse(); //Done
            List <StudentClass>       lxSC            = AddStudentClass();       //Done
            List <StudentTest>        lxStudentTest   = AddStudentTest();        //Done

            List <Test>     lxTest     = AddTest();                              //Done
            List <User>     lxUser     = AddUser();                              //Done
            List <UserTest> lxUserTest = AddUserTest();                          //Done

            #region UsingDB
            //using (var db = new DbModel())
            //{
            //    foreach (var item in lxOcc)
            //    {
            //        db.Occupations.Add(item);
            //    }
            //    db.SaveChanges();
            //}
            //using (var db = new DbModel())
            //{
            //    foreach (var item in lxCourse)
            //    {
            //        db.Courses.Add(item);
            //    }
            //    db.SaveChanges();
            //}
            //using (var db = new DbModel())
            //{
            //    foreach (var item in lxSC)
            //    {
            //        db.StudentClasses.Add(item);
            //    }
            //    db.SaveChanges();
            //}
            //using (var db = new DbModel())
            //{
            //    foreach (var item in lxSGC)
            //    {
            //        db.StudentClassCourses.Add(item);
            //    }
            //    db.SaveChanges();
            //}
            //using (var db = new DbModel())
            //{
            //    foreach (var item in lxStudent)
            //    {
            //        db.Students.Add(item);
            //    }
            //    db.SaveChanges();
            //}
            //using (var db = new DbModel())
            //{

            //    foreach (var item in lxUser)
            //    {
            //        db.Users.Add(item);
            //    }
            //    db.SaveChanges();
            //}
            //using (var db = new DbModel())
            //{
            //    foreach (var item in lxTest)
            //    {
            //        db.Tests.Add(item);
            //    }
            //    db.SaveChanges();
            //}
            //using (var db = new DbModel())
            //{
            //    foreach (var item in lxUserTest)
            //    {
            //        db.UserTests.Add(item);
            //    }
            //    db.SaveChanges();
            //}
            //using (var db = new DbModel())
            //{
            //    foreach (var item in lxQuestions)
            //    {
            //        db.Questions.Add(item);
            //    }
            //    db.SaveChanges();
            //}
            //using (var db = new DbModel())
            //{
            //    foreach (var item in lxAnswer)
            //    {
            //        db.Answers.Add(item);
            //    }
            //    db.SaveChanges();
            //}

            using (var db = new DbModel())
            {
                foreach (var item in lxStudentTest)
                {
                    db.StudentTests.Add(item);
                }
                db.SaveChanges();
            }
            #endregion
        }