Code First - 在没有专门的 DbContext 的情况下持久保存对象
Code First 是一个很棒的功能。但我无法弄清楚如何在不首先创建专门的 DbContext 的情况下持久保存对象。有可能吗?我想看到一些类似的内容:
var dbConn = new SqlCeConnection("Data Source=Test.sdf");
using (var db = new DbContext(dbConn, true))
{
var cmp = new Company { CompanyName = "Microsoft" };
db.Set(typeof(Company)).Add(cmp);
var recordsAffected = db.SaveChanges();
Console.WriteLine(
"Saved {0} entities to the database, press any key to exit.",
recordsAffected);
Console.ReadKey();
}
是否可以动态注册用于模型创建的类?一定有办法的!
Code First is a terrific feature. But I could not figure out how to persist an object without creating a specialized DbContext first. Is it possible at all? I'd like to see something along these lines:
var dbConn = new SqlCeConnection("Data Source=Test.sdf");
using (var db = new DbContext(dbConn, true))
{
var cmp = new Company { CompanyName = "Microsoft" };
db.Set(typeof(Company)).Add(cmp);
var recordsAffected = db.SaveChanges();
Console.WriteLine(
"Saved {0} entities to the database, press any key to exit.",
recordsAffected);
Console.ReadKey();
}
Is it possible to dynamically register a class for model creation? There must be a way!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,据我所知,在没有任何映射信息的情况下不可能创建
DbContext
。定义映射和数据库初始化需要具有预定义 DbSet 的专用上下文。仅当您通过传递在使用DbContext
之前手动创建的DbCompiledModel
来提供有关通过其构造函数映射的信息时,您才可以使用基本 DbContext,但我还没有尝试过。问题在于 DbSets 和重写的
OnModelCreating
用于推断所需的映射。如果您没有定义 DbSets 或OnModelCreating
,则DbContext
无法推断和缓存映射。对于每个上下文类型,映射元数据仅创建和编译一次(直到应用程序重新启动)。此操作被认为非常慢。如果您没有特定的上下文类型 EF 可能无法推断映射,即使可以,它也可能需要为上下文的每个实例创建和编译元数据(如匿名类型)。如果您使用手动创建的
DbCompiledModel
,则您有责任重用它。No, as I know there is not any possibility to create
DbContext
without any information about mapping. Specialized context with predefined DbSets is necessary to define mappings and database initialization. You can probably use base DbContext only if you provide informations about mapping through its constructor by passingDbCompiledModel
created manually before usingDbContext
but I haven't tried this yet.The problem is that DbSets and overriden
OnModelCreating
are used to infer needed mapping. If you don't have DbSets orOnModelCreating
definedDbContext
can't infer and cache mapping. Mapping metadata are created and compiled only once for each context type (until application restarts). This operation is considered as very slow. If you don't have specific context type EF can't probably infer mapping and even if it can it will probably need to create and compile metadata for each instance of the context (like for anonymous types).If you use
DbCompiledModel
created manually it will be your responsibility to reuse it.