使用具有流畅api的复合外键配置一对一或一对一关系

时间:2014-06-03 11:33:12

标签: c# .net entity-framework ef-code-first

我正在使用Entity Framework 6.1.0开发C#.NET Framework 4.0。

我有一个现有的数据库,我用它生成了Code First类。

这些是我的课程:

[Table("CODES")]
public partial class CODE
{
    public CODE()
    {
    }

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long ID_CODE { get; set; }

    [Key]
    [Column(Order = 0)]
    public byte CODE_LEVEL { get; set; }

    [Key]
    [Column("CODE", Order = 1)]
    [StringLength(20)]
    public string CODE1 { get; set; }

    public byte? COMMISIONING_FLAG { get; set; }

    public bool? IS_TRANSMITTED { get; set; }

    public DateTime? TIMESPAN { get; set; }

    [StringLength(50)]
    public string USERNAME { get; set; }

    [StringLength(50)]
    public string SOURCE { get; set; }

    public virtual AGGREGATION_CHILDS AGGREGATION_CHILDS { get; set; }

    public virtual AGGREGATION AGGREGATIONS { get; set; }
}

public partial class AGGREGATION_CHILDS
{
    [Key]
    [Column(Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public long ID_AGGREGATION { get; set; }

    [Key]
    [Column(Order = 1)]
    [StringLength(20)]
    public string ID_CHILD { get; set; }

    [Key]
    [Column(Order = 2)]
    public byte CODE_LEVEL { get; set; }

    public int POSITION { get; set; }

    public virtual AGGREGATION AGGREGATION { get; set; }

    public virtual CODE CODE { get; set; }
}

[Table("AGGREGATIONS")]
public partial class AGGREGATION
{
    public AGGREGATION()
    {
        AGGREGATION_CHILDS = new HashSet<AGGREGATION_CHILDS>();
    }

    [Key]
    public long ID_AGGREGATION { get; set; }

    [StringLength(20)]
    public string ID_PARENT { get; set; }

    public byte? PARENT_LEVEL { get; set; }

    public virtual ICollection<AGGREGATION_CHILDS> AGGREGATION_CHILDS { get; set; }

    public virtual CODE CODE { get; set; }
}

模特:

public partial class MyDbContext : DbContext
{
    public MyDbContext()
        : base("name=MyDbContext")
    {
    }

    public virtual DbSet<AGGREGATION_CHILDS> AGGREGATION_CHILDS { get; set; }
    public virtual DbSet<AGGREGATION> AGGREGATIONS { get; set; }
    public virtual DbSet<CODE> CODES { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<AGGREGATION>()
            .HasMany(e => e.AGGREGATION_CHILDS)
            .WithRequired(e => e.AGGREGATION)
            .WillCascadeOnDelete(false);
    }
}

CODES主键为(CODE_LEVEL, CODE1)

我在CODESAGGREGATION_CHILDS之间建立了一对一的关系。

CODES.CODE1      -> AGGREGATION_CHILDS.ID_CHILD
CODES.CODE_LEVEL -> AGGREGATION_CHILDS.CODE_LEVEL

CODESAGGREGATION之间的另一个一对一关系。

CODES.CODE1      -> AGGREGATION.ID_PARENT
CODES.CODE_LEVEL -> AGGREGATION.PARENT_LEVEL

但在AGGREGATION中,外键是可选的:ID_PARENTPARENT_LEVEL可以是NULL

如何在OnModelCreating上设置这两种关系?

0 个答案:

没有答案