c# - Entity Framework 对较小的桌面应用程序有意义吗?

标签 c# ios .net entity-framework sqlite

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

过去,我只是简单地使用了 SQLite 包装类,它们除了允许您将 SQL 作为操作或查询对数据库执行外,几乎什么都不做。一点也不花哨。

我想知道的是,我看到 Entity Framework 也支持 SQLite,至少在 Windows 方面是这样。我想知道使用它是否更有意义,或者我是否应该坚持使用相同的、简单的直接 SQL 模式,因为我基本上必须在其他平台上这样做。但与我交谈过的很多人一直在说 EF6.x 现在有多棒。

我还记得我们过去的 ADO.NET 数据集时代,我们喜欢数据集的可视化设计器来设置表、键、关系等。我希望能够使用它或类似的东西,但是我可以在下面的代码中使用 [Table] 和 [Column] 等属性。

想法?

更新...

我知道 SQLite 不支持 Code First,但我实际上开发了一个 SQLiteContextInitializer,它确实允许我在 Code-first 场景中做我需要的几乎所有事情。这是供引用/增强。我在网上找到了其他人的类似版本,并对其进行了增强以正确使用 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);
        }
    }
}

最佳答案

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

ORM 的好处:

  • 缩短开发时间
  • 开发人员可以在更加以应用程序为中心的对象模型方面工作
  • 应用程序摆脱了对特定数据引擎的硬编码依赖
  • 语言集成查询支持(称为 LINQ to Entities)

这是从这里https://msdn.microsoft.com/en-us/data/aa937709.aspx

关于c# - Entity Framework 对较小的桌面应用程序有意义吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30419057/

相关文章:

c# - 如何使用 Moq 修改模拟方法的调用参数?

c# - 如何在 .NET Winforms 的按钮组中一次选择一个按钮

ios - 更新应用程序时,iPhone 中的所有本地文件都会被删除

ios - 如何阻止背景阻止 Swift 4 中的其他元素?

ios - Alamofire 上传巨大的文件

c# - 找不到程序集

C# 一个项目可以有多个 .config 文件吗?

C# 验证字段的更好方法。 (Linq 到 SQL)

.net - Microsoft HPC任务的错误处理策略

c++ - C 是.NET 框架的一部分吗?