我正在使用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)
。
我在CODES
和AGGREGATION_CHILDS
之间建立了一对一的关系。
CODES.CODE1 -> AGGREGATION_CHILDS.ID_CHILD
CODES.CODE_LEVEL -> AGGREGATION_CHILDS.CODE_LEVEL
CODES
和AGGREGATION
之间的另一个一对一关系。
CODES.CODE1 -> AGGREGATION.ID_PARENT
CODES.CODE_LEVEL -> AGGREGATION.PARENT_LEVEL
但在AGGREGATION
中,外键是可选的:ID_PARENT
和PARENT_LEVEL
可以是NULL
。
如何在OnModelCreating
上设置这两种关系?