简体   繁体   English

如何在代码优先中定义0..1到多的关系

[英]How to define a 0..1 to many relationship in code-first

I'm reading ado.net team blog's articles these days, when I find how to create one to one relationship, one to many relationship and many to many relationship. 这些天,当我发现如何创建一对一关系,一对多关系和多对多关系时,我正在阅读ado.net团队博客的文章。 But, is there a way to create 0..1 to many relationship? 但是,有没有一种方法可以创建多个关系0..1?

class TestA
{
    public int id { get; set; }
    public string name { get; set; }
    [Timestamp]
    public byte[] stamp { get; set; }       
    public TestB TB { get; set; }
}

class TestB
{
    public int id { get; set; }
    public string name { get; set; }
    [Timestamp]
    public byte[] stamp { get; set; }
    public ICollection<TestA> TA { get; set; }
}

class myContext : DbContext
{
    public DbSet<TestA> players { get; set; }
    public DbSet<TestB> teams { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<TestB>().HasOptional<TestA>(a => a);
    }
}

Thx inadvance! 谢谢!

You are almost there. 你快到了。 Try mapping it as follows. 尝试按以下方式映射它。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<TestA>().HasOptional(a => a.TB)
       .WithMany(b => b.TA);
}

Articles on mapping 映射文章

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 EF代码优先1:相同模型之间的1:* 1:0..1关系 - EF code-first 1:* 1:0..1 relationship between the same models 如何使用代码优先正确初始化多对多关系 - How to correctly initialize many to many relationship with code-first 实体框架核心代码优先-0..1至多关系和级联删除 - Entity Framework Core code first - 0..1 to many relationship and cascade delete Code-First EF4中的多对多关系 - Many-To-Many Relationship in Code-First EF4 实体框架代码优先在同一个表上的多对多关系 - Entity Framework Code-first Many to many relationship on the same table 多对多关系中不完整的EF代码优先级联删除 - Incomplete EF code-first cascade delete on many to many relationship 实体框架,代码优先,如何从多对多关系映射中向表添加主键? - Entity Framework, code-first, how to add primary key to table out of many-to-many relationship mapping? 如何定义EF代码优先三方FK关系? (父母有两个相关的孩子) - How to define EF code-first tri-way FK relationship? (parent with two related children) 如何使3个实体之间的一对多关系与Entity Framework Core 2.1一起使用 - 代码优先 - How to make one-to-many relationship between 3 entities work with Entity Framework Core 2.1 - code-first 使用 MVC 3 Entity Framework Code-First,如何以一对多的关系创建一个新的“多”object? - Using MVC 3 Entity Framework Code-First, how do you create a new “many” object in a one-to-many relationship?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM