实体框架对小型桌面应用程序有意义吗?

时间:2015-05-24 00:54:13

标签: c# ios .net entity-framework sqlite

我正在创建一个相对较小的基于数据库的应用程序(大约20个表和最多20K行。我们将使用SQLite,因为我们想支持Windows OS X,iPhone / iPad和Android并且需要轻松移动文件,因此SQLite绝对是正确的选择。

现在在过去,我只使用了SQLite包装类,除了允许您作为操作或查询对数据库执行SQL之外几乎什么都不做。没什么太奇特的。

我想知道的是,我发现实体框架也支持SQLite,至少在Windows方面是这样。我想知道使用它是否更有意义,或者我是否应该坚持使用相同的,简单的直接SQL模式,因为我基本上必须在其他平台上这样做。但是我和很多人一直在谈论EF6.x现在有多棒了。

我还记得我们旧的ADO.NET数据集日,我们喜欢DataSet的视觉设计师,用于设置表格,键,关系等。我很乐意有能力使用它或类似的东西,但是[Table]和[Column]等属性,我可以使用下面的代码。

思想?

更新...

我知道SQLite不支持Code First,但我实际上已经开发了一个SQLiteContextInitializer, 允许我在代码优先的场景中完成我需要的几乎所有工作。这里是供参考/增强的。我在网上找到了其他类似的东西,并对其进行了增强,以正确使用TableName属性等。享受!

class SqliteContextInitializer<T> : IDatabaseInitializer<T>
where T : SQLiteContext<T>
{
    private readonly bool _dbExists;
    private readonly DbModelBuilder _modelBuilder;

    public delegate void BeforeCreateDatabaseDelegate(DbModel model, out bool autoGenerateSchema);
    public readonly BeforeCreateDatabaseDelegate BeforeCreateDatabase;

    public delegate void AfterCreateDatabaseDelegate(DbModel model);
    public readonly AfterCreateDatabaseDelegate AfterCreateDatabase;

    public SqliteContextInitializer(string dbPath, DbModelBuilder modelBuilder, BeforeCreateDatabaseDelegate beforeCreateDatabase = null, AfterCreateDatabaseDelegate afterCreateDatabase = null)
    {
        _dbExists = File.Exists(dbPath);
        _modelBuilder = modelBuilder;
        BeforeCreateDatabase = beforeCreateDatabase;
        AfterCreateDatabase = afterCreateDatabase;
    }

    public void InitializeDatabase(T context)
    {
        if (_dbExists)
            return;

        var model = _modelBuilder.Build(context.Database.Connection);

        using (var transaction = context.Database.BeginTransaction())
        {
            try
            {
                bool autoGenerateSchema = true;

                if(BeforeCreateDatabase != null)
                    BeforeCreateDatabase(model, out autoGenerateSchema);

                if (autoGenerateSchema)
                {
                    AutoCreateSchema(context.Database, model);

                    if(AfterCreateDatabase != null)
                        AfterCreateDatabase(model);
                }

                transaction.Commit();
            }
            catch (Exception)
            {
                transaction.Rollback();
                throw;
            }
        }
    }

    class Index
    {
        public string Name { get; set; }
        public string Table { get; set; }
        public List<string> Columns { get; set; }
    }

    private void AutoCreateSchema(Database db, DbModel model)
    {
        const string tableTemplate      = "CREATE TABLE [{0}] (\n{1}\n);";
        const string columnTemplate     = "    [{0}] {1} {2}"; // name, type, decl
        const string primaryKeyTemplate = "    PRIMARY KEY ({0})";
        const string foreignKeyTemplate = "    FOREIGN KEY ({0}) REFERENCES {1} ({2})";
        const string indexTemplate      = "CREATE INDEX {0} ON {1} ({2});";

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

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

            // columns
            foreach (var columnInfo in tableInfo.Properties)
            {
                var columnDeclarations = new HashSet<string>();

                if (!columnInfo.Nullable)
                    columnDeclarations.Add("NOT NULL");

                var indexAnnotations = columnInfo.MetadataProperties
                    .Select(x => x.Value)
                    .OfType<IndexAnnotation>();

                foreach (var indexAnnotation in indexAnnotations)
                {
                    foreach (var indexAttribute in indexAnnotation.Indexes)
                    {
                        if (indexAttribute.IsUnique)
                            columnDeclarations.Add("UNIQUE");

                        if (string.IsNullOrEmpty(indexAttribute.Name))
                            continue;

                        Index index;
                        if (!indicies.TryGetValue(indexAttribute.Name, out index))
                        {
                            index = new Index
                            {
                                Name = indexAttribute.Name,
                                Table = tableInfo.Name,
                                Columns = new List<string>(),
                            };
                            indicies.Add(index.Name, index);
                        }
                        index.Columns.Add(columnInfo.Name);
                    }
                }

                // Add column definition record
                var columnDefinitionRecord = string.Format(columnTemplate,
                    columnInfo.Name, // Unlike with tables, this picks up the attribute-specified value
                    columnInfo.TypeName,
                    string.Join(" ", columnDeclarations));

                tableDefinitionRecords.Add(columnDefinitionRecord);
            }

            // primary keys
            if (tableInfo.KeyProperties.Any()) // then add primary key definition record
            {
                var primaryKeyColumnNames = tableInfo.KeyProperties.Select(x => x.Name);

                var primaryKeyRecord = string.Format(primaryKeyTemplate,
                    string.Join(", ", primaryKeyColumnNames));

                tableDefinitionRecords.Add(primaryKeyRecord);
            }

            // foreign keys
            foreach (var assoc in model.StoreModel.AssociationTypes)
            {
                if (assoc.Constraint.ToRole.Name == tableInfo.Name)
                {
                    var toKeyColumnNames = assoc.Constraint.ToProperties.Select(x => x.Name);
                    var fromKeyColumnNames = assoc.Constraint.FromProperties.Select(x => x.Name);

                    // Add foreign key definition record
                    var foreignKeyDefinitionRecord = string.Format(foreignKeyTemplate,
                        string.Join(", ", toKeyColumnNames),
                        assoc.Constraint.FromRole.Name,
                        string.Join(", ", fromKeyColumnNames));

                    tableDefinitionRecords.Add(foreignKeyDefinitionRecord);
                }
            }

            MetadataProperty tableNameProperty;
            var tableName = tableInfo.MetadataProperties.TryGetValue("TableName", true, out tableNameProperty)
                ? tableNameProperty.Value
                : tableInfo.Name;

            // Create table
            var sql = string.Format(tableTemplate,
                tableName,
                string.Join(",\n", tableDefinitionRecords));

            db.ExecuteSqlCommand(sql);
        }

        // create indexes for all tables
        foreach (var index in indicies.Values)
        {
            var columns = string.Join(", ", index.Columns);

            var sql = string.Format(indexTemplate,
                index.Name,
                index.Table,
                columns);

            db.ExecuteSqlCommand(sql);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

使用ORM是有意义的。问题是哪一个?

ORM的好处:

  • 缩短开发时间
  • 开发人员可以使用更加以应用程序为中心的对象模型
  • 应用程序从特定数据引擎的硬编码依赖项中解脱出来
  • 语言集成查询支持(称为LINQ to Entities)

这是来自https://msdn.microsoft.com/en-us/data/aa937709.aspx