【发布时间】:2013-02-16 19:57:28
【问题描述】:
我想为实体框架实现几个扩展。 让我们以这个为例。
void InsertOrUpdate<T, TUpdateFields, TInsertFields, TKey>(
this DbContext context,
IEnumerable<T> data,
Expression<Func<T, TUpdateFields>> updateFields,
Expression<Func<T, TInsertFields>> insertFields,
Expression<Func<T, TKey>> key)
而且应该是这样使用的。
var dc = new SomeContext();
var user = new User() { /* initialize */ };
var array = new[] { user };
dc.InsertOrUpdate(
array,
x => new {
x.UserName,
x.Password,
x.LastLoggedIn
},
x => new {
x.UserName,
x.Password,
x.Email,
x.DateAdded,
x.LastLoggedIn
},
x => x.UserName);
该方法将生成一个 sql 字符串并将其传递给DbContext.Database.ExecuteSqlCommand 方法。
但是为了生成sql,我需要从模型信息中提取表名和字段名,以防它们与类名和属性名不同。
(例如UserName属性对应DB中的user_name字段)
我知道它们可以在实体本身中设置为数据注解,直接在OnModelCreating(DbModelBuilder)方法中定义在modelbuilder中
DbContext 或以EntityTypeConfiguration<T> 实现的形式定义,并以相同的方法传递到模型构建器配置中。
如何从 DbContext 实例中检索表和字段的名称? 有可能吗?
【问题讨论】:
标签: .net entity-framework-5 entity-framework-4.3