こんにちは、CTP4 からのみ Entity Framework コードを使用しています。私の質問はこれです: EntityConfiguration を使用してマップされたドメイン クラスの名前が与えられた場合、実行時にマップされたクラスのテーブル名を取得するにはどうすればよいですか? ObjectContext で MetadataWorkspace を使用する必要があると想定していますが、最新のドキュメントを入手するのは難しいと感じています。ヘルプやリンクをいただければ幸いです。ありがとう。
1 に答える
1
はい、その通りです。すべてのマッピング情報は、MetadataWorkspace から取得できます。
Product
以下は、クラスのテーブル名とスキーマ名を取得するコードです。
public class Product
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class ProductConfiguration : EntityTypeConfiguration<Product>
{
public ProductConfiguration()
{
HasKey(e => e.Id);
Property(e => e.Id)
.HasColumnName(typeof(Product).Name + "Id");
Map(m =>
{
m.MapInheritedProperties();
m.ToTable("ProductsTable");
});
Property(p => p.Name)
.IsRequired()
.IsUnicode();
}
}
public class Database : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ProductConfiguration());
}
public DbSet<Product> Products { get; set; }
}
ここで、クラスのテーブル名を取得するにProduct
は、DbContext を作成し、次のコードを使用する必要があります。
using(var dbContext = new Database())
{
var adapter = ((IObjectContextAdapter)dbContext).ObjectContext;
StoreItemCollection storageModel = (StoreItemCollection)adapter.MetadataWorkspace.GetItemCollection(DataSpace.SSpace);
var containers = storageModel.GetItems<EntityContainer>();
EntitySetBase productEntitySetBase = containers.SelectMany(c => c.BaseEntitySets.Where(bes => bes.Name == typeof(Product).Name)).First();
// Here are variables that will hold table and schema name
string tableName = productEntitySetBase.MetadataProperties.First(p => p.Name == "Table").Value.ToString();
string schemaName = productEntitySetBase.MetadataProperties.First(p => p.Name == "Schema").
}
これが完璧な解決策であるとは思えませんが、以前使用していたので問題なく動作しました。
于 2013-01-30T17:27:56.953 に答える