所有,我有一个问题,我不知道如何使用实体框架代码。现在我有 2 表TbA和TbB
create table TbA
(
[id] int not null identity(1,1) constraint [PK_TbA] primary key,
[name] varchar(50) not null
)
create table TbB
(
[id] int not null identity(1,1) constraint [PK_TbB] primary key,
[name] varchar(50) not null,
[TbAId] int not null
)
在数据库中,他们没有使用 forgin 密钥。
这是我的代码,我不知道如何映射看起来像这样的一对一关系
class Program
{
static void Main(string[] args)
{
string connectionString = "data source=localhost;database=demo;Integrated Security=True";
MyDbContext db = new MyDbContext(connectionString);
db.TbA.AsParallel().ForAll(x => {
Console.WriteLine("{0}----{1}", x.TbAId, x.TbAName);
});
//here is throw error
db.TbB.AsParallel().ForAll(x => {
Console.WriteLine("{0}--{1}--{2}--{3}", x.TbBId, x.TbBName, x.MyTbA.TbAId, x.MyTbA.TbAName);
});
Console.ReadLine();
}
}
public class MyDbContext : DbContext
{
public DbSet<TbA> TbA { get; set; }
public DbSet<TbB> TbB { get; set; }
public MyDbContext(string connectionString)
: base(connectionString)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new TbAMapping());
modelBuilder.Configurations.Add(new TbBMapping());
base.OnModelCreating(modelBuilder);
}
}
public class TbA
{
public int TbAId { get; set; }
public string TbAName { get; set; }
}
public class TbB
{
public int TbBId { get; set; }
public string TbBName { get; set; }
public TbA MyTbA { get; set; }
}
public class TbAMapping : EntityTypeConfiguration<TbA>
{
public TbAMapping()
{
ToTable("TbA");
HasKey(x => x.TbAId);
Property(x => x.TbAId).IsRequired().HasColumnName("Id");
Property(x => x.TbAName).IsRequired().HasColumnName("Name");
}
}
public class TbBMapping : EntityTypeConfiguration<TbB>
{
public TbBMapping()
{
ToTable("TbB");
HasKey(x => x.TbBId);
Property(x => x.TbBId).IsRequired().HasColumnName("Id");
Property(x => x.TbBName).IsRequired().HasColumnName("Name");
// here, how to setting the mapping the TbA.Id to here
}
}