我正在创建一个相对较小的基于数据库的应用程序(约 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)
关于c# - Entity Framework 对较小的桌面应用程序有意义吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30419057/