我首先使用Entity Framework 4.3.1代码。我的数据库中有2个表,列出了列名:
状态表:
StatusID int
Status varchar(50)
RequestStatuses表:
RequestStatusID int
RequestStatus varchar(50)
我有2个班级:
public class Status : IEntity
{
public int Id { get; set; }
public string Name { get; set; }
public RequestStatus RequestStatus { get; set; }
}
public class RequestStatus : IEntity
{
public int Id { get; set; }
public string Name { get; set; }
public Status Status { get; set; }
}
我的数据库上下文类:
public class ICaseDbContext : DbContext
{
public DbSet<Status> Statuses { get; set; }
public DbSet<RequestStatus> RequestStatuses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new StatusConfiguration());
modelBuilder.Configurations.Add(new RequestStatusConfiguration());
}
}
他们的配置:
class StatusConfiguration : EntityTypeConfiguration<Status>
{
internal StatusConfiguration()
{
this.ToTable("Statuses");
this.Property(x => x.Id).HasColumnName("StatusID");
this.Property(x => x.Name).HasColumnName("Status");
}
}
class RequestStatusConfiguration : EntityTypeConfiguration<RequestStatus>
{
internal RequestStatusConfiguration()
{
this.ToTable("RequestStatuses");
this.Property(x => x.Id).HasColumnName("RequestStatusID");
this.Property(x => x.Name).HasColumnName("RequestStatus");
}
}
每个表格中的数据如下:
RequestStatuses表:
RequestStatusID RequestStatus
1 RequestStatus1
2 RequestStatus2
3 RequestStatus3
4 RequestStatus4
状态表:
StatusID Status
1 Status1
2 Status2
3 Status3
4 Status4
每个表的主键与另一个表中的主键匹配。因此,如果我的请求状态为RequestStatus1,则相应的状态必须为Status1。如果状态为Status3,则相应的请求状态必须为RequestStatus3。
这可能吗?
如何在EF
中设置thtis答案 0 :(得分:0)
我认为你想要一个1:1的映射,所以两端都是必需的,使用Id作为密钥。
更新这样的配置将创建您想要的表:
class StatusConfiguration : EntityTypeConfiguration<Status>
{
internal StatusConfiguration()
{
this.ToTable("Statuses");
this.Property(x => x.Id).HasColumnName("StatusID");
this.Property(x => x.Name).HasColumnName("Status");
this.HasRequired(x => x.RequestStatus)
.WithRequiredPrincipal();
}
}
class RequestStatusConfiguration : EntityTypeConfiguration<RequestStatus>
{
internal RequestStatusConfiguration()
{
this.ToTable("RequestStatuses");
this.Property(x => x.Id).HasColumnName("RequestStatusID");
this.Property(x => x.Name).HasColumnName("RequestStatus");
this.HasRequired(x => x.Status)
.WithRequiredDependent();
}
}