我遇到了Code first和生成的sql数据库的问题。
关于公牛和奶牛的申请
以下是我的课程:
public class Animal : BaseEntity
{
public virtual int? DeathId { get; set; }
public virtual Death Death { get; set; }
public virtual int? SellId { get; set; }
public virtual Sell Sell { get; set; }
}
public class Death : Event
{
public virtual int AnimalId { get; set; }
public virtual Animal Animal { get; set; }
}
public class Sell : Event
{
public virtual int AnimalId { get; set; }
public virtual Animal Animal { get; set; }
}
生成这个sql脚本:
create table [dbo].[Animal] (
[Id] [int] not null identity,
[DeathId] [int] null,
[SellId] [int] null,
primary key ([Id])
);
create table [dbo].[Death] (
[Id] [int] not null,
[AnimalId] [int] not null,
primary key ([Id])
);
create table [dbo].[Sell] (
[Id] [int] not null,
[AnimalId] [int] not null,
primary key ([Id])
);
一切正常,但问题在于这些类:
public class Servicie : Event
{
public virtual int MaleId { get; set; }
public virtual Male Male { get; set; }
public virtual int FemaleId { get; set; }
public virtual Female Female { get; set; }
public virtual int? ChildbirthId { get; set; }
public virtual Childbirth Childbirth { get; set; }
}
public class Childbirth : Event
{
public virtual int ServicieId { get; set; }
public virtual Servicie Servicie { get; set; }
public virtual int FemaleId { get; set; }
public virtual Female Female { get; set; }
}
这些类生成此Sql脚本:
create table [dbo].[Service] (
[Id] [int] not null,
[MaleId] [int] not null,
[FemaleId] [int] not null,
[ChildbirthId] [int] null,
primary key ([Id])
);
create table [dbo].[Parto] (
[Id] [int] not null,
[Servicie_Id] [int] not null,
[ServicieId] [int] not null,
[FemaleId] [int] not null,
primary key ([Id])
);
正如你所看到的,还有“ServicieId”和“Servicie_Id”,最后一个,自动添加。
所有都是1到0..1的关系,我没有看到任何差异,有人可以帮助我吗?
答案 0 :(得分:0)
编辑 - 添加了整个测试应用程序:
当我使用这个模型时(你的简化版本)。我不得不添加一个必需的注释,因此EF知道哪个是主体,哪个是从属端,它感到困惑。
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Text;
namespace CFExamples2
{
public class Servicio
{
public int Id { get; set; }
public int? PartoId { get; set; }
public virtual Parto Parto { get; set; }
}
public class Parto
{
public int Id { get; set; }
public virtual int ServicioId { get; set; }
[Required]
public virtual Servicio Servicio { get; set; }
}
public class Model : DbContext
{
public DbSet<Servicio> Servicios { get; set; }
public DbSet<Parto> Partos { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
class Program
{
static void Main(string[] args)
{
}
}
}
它产生了这个: