【发布时间】:2015-01-16 15:23:03
【问题描述】:
我有一个现有的数据库,并希望使用 EF Code First 和 Fluent API 将我的实体与数据库中的表进行映射。
我的桌子是:
Bank(KeyB, BankName) - KeyB 是 PrimaryKey
User(KeyU, UserName, KeyB) - KeyU 是 PrimaryKey,KeyB 有外键,可以为空。
我有这些实体:
class Bank
{
public int Id;
public string Name;
}
class User
{
public int KeyU;
public Bank Bank;
}
我无法让我的 0 对 1 关联与 fluent API 一起使用。 我尝试在 User 实体中添加一个可为空的 int 属性 BankId(如果可能的话,我希望能够避免这种情况)并将以下代码添加到映射中,但没有成功:
class UserMap:EntityTypeConfiguration<User>
{
public UserMap()
{
this.HasKey(u => u.KeyU);
this.Property(u => u.BankId).HasColumnName("KeyB");
this.HasOptional(u => u.Bank).WithMany().HasForeignKey(u => u.BankId);
}
}
User 实例中的 Bank 属性始终为 null。
您对如何实现这一点有任何想法吗?
[更新] 我现在有以下代码仍然无法正常工作:
class TestCFContext:DbContext
{
public TestCFContext():base(ConnectionString())
{}
private static string ConnectionString()
{return "Data Source=.;Initial Catalog=Test;Integrated Security=SSPI;";}
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new UserMap());
modelBuilder.Configurations.Add(new BankMap());
}
}
class UserMap:EntityTypeConfiguration<User>
{
public UserMap()
{
this.HasKey(u => u.Id);
this.Property(u => u.Id).HasColumnName("KeyU");
this.HasOptional(u => u.Bank).WithMany().Map(c => c.MapKey("KeyB"));
this.ToTable("Users");
}
}
class BankMap:EntityTypeConfiguration<Bank>
{
public BankMap()
{
this.HasKey(b => b.Id);
this.Property(b => b.Id).HasColumnName("KeyB");
this.ToTable("Banks");
}
}
class Bank
{
public int Id { get; set; }
public string Name { get; set; }
}
class User
{
public int Id { get; set; }
public string Name { get; set; }
public virtual Bank Bank { get; set; }
}
static void Main(string[] args)
{
var c = new TestCFContext();
foreach (var u in c.Users)
{
Console.WriteLine(u.Bank.Id);
}
}
【问题讨论】:
标签: c# entity-framework c#-4.0 ef-code-first