代码第一个Entity Framework外键约束

时间:2016-05-04 09:11:26

标签: c# sql sql-server

Property.csPaymentDetailId但在迁移期间未被指定为外键

    public long CountryId { get; set; }
    public virtual Country Country { get; set; }

    [Required]
    public bool IsDeleted { get; set; }
    public int RoomsAvailable { get; set; }

    [DefaultValue(0), Required]
    public int Order { get; set; }

    public long? PaymentDetailId { get; set; }
    public virtual PaymentDetail PaymentDetail { get; set; }

PaymentDetail.cs PropertyId是PaymentDetails中的外键,但PaymentDetailId不是属性表中的外键

     public long PropertyId { get; set; }
    public virtual Property Property { get; set; }

    [StringLength(200)]
    public string AccountNumber { get; set; }
    [StringLength(100)]
    public string IFSCCode { get; set; }
    [StringLength(200)]
    public string Name { get; set; }

Fluent api补充道:

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
     modelBuilder.Entity<Property>().HasOptional(p =>p.PaymentDetail).
     WithRequired(d => d.Property).WillCascadeOnDelete();
     base.OnModelCreating(modelBuilder);
 }

遇到以下错误:

  

INSERT语句与FOREIGN KEY约束冲突&#34; FK_dbo.PaymentDetails_dbo.Properties_Id&#34;。冲突发生在数据库&#34; QikStay.DAL.QikStayDataContext&#34;,table&#34; dbo.Properties&#34;,column&#39; Id&#39;。

迁移文件:

 public partial class propertypaymentdetail : DbMigration
{
    public override void Up()
    {
        CreateTable(
            "dbo.PaymentDetails",
            c => new
                {
                    Id = c.Long(nullable: false),
                    PropertyId = c.Long(nullable: false),
                    AccountNumber = c.String(maxLength: 200),
                    IFSCCode = c.String(maxLength: 100),
                    Name = c.String(maxLength: 200),
                    CreateTime = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"),
                    UpdateTime = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"),
                })
            .PrimaryKey(t => t.Id)
            .ForeignKey("dbo.Properties", t => t.Id)
            .Index(t => t.Id);

        AddColumn("dbo.Properties", "PaymentDetailId", c => c.Long());
    }

    public override void Down()
    {
        DropForeignKey("dbo.PaymentDetails", "Id", "dbo.Properties");
        DropIndex("dbo.PaymentDetails", new[] { "Id" });
        DropColumn("dbo.Properties", "PaymentDetailId");
        DropTable("dbo.PaymentDetails");
    }
}

}

这是解决问题的正确流畅的api

  

modelBuilder.Entity<Property>()
 .HasOptional(a => a.PaymentDetail)
 .WithMany()
 .HasForeignKey(u => u.PaymentDetailId);

0 个答案:

没有答案