0

所有,我有一个问题,我不知道如何使用实体框架代码。现在我有 2 表TbATbB

    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
    }
}
4

1 回答 1

0


首先,您必须将 TbA MyTbA 声明为虚拟的,

public virtual TbA MyTbA{get;set;}
(*)public int TbAid{get;set;}

然后你可以在 typeConfiguration 上配置你的关系。
但是你需要在 B 类中有一个 foreignKeytoA。(*)

HasRequired(x=>x.MyTbA).WithOptional().HasForeignKey(x=>x.ForeignKeytoA);

如果你把

.withOptional(empty).

告诉实体 A 类没有 B 的外键。

于 2013-07-18T11:46:40.430 回答