【发布时间】:2017-01-09 18:45:16
【问题描述】:
我正在尝试在 File 和 AMCN 这两个模型之间创建一对多的关系。这是我的文件:
public class File
{
public int Id { get; set; }
public int AmcnId { get; set; }
[StringLength(255)]
public string FileName { get; set; }
[StringLength(100)]
public string ContentType { get; set; }
public byte[] Content { get; set; }
public virtual AMCN Amcn { get; set; }
}
这是我的 AMCN 的一部分:
public class AMCN
{
public int Id { get; set; }
public DateTime Created { get; set; }
//lots of other data here...
public virtual ICollection<File> Files { get; set; }
public virtual ICollection<FoSL> FoSLs { get; set; }
}
所以我进入包管理器控制台,执行add-migration files,它工作并生成了这个:
public partial class files : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Files",
c => new
{
Id = c.Int(nullable: false, identity: true),
AmcnId = c.Int(nullable: false),
FileName = c.String(maxLength: 255),
ContentType = c.String(maxLength: 100),
Content = c.Binary(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AMCNs", t => t.AmcnId, cascadeDelete: true)
.Index(t => t.AmcnId);
}
public override void Down()
{
DropForeignKey("dbo.Files", "AmcnId", "dbo.AMCNs");
DropIndex("dbo.Files", new[] { "AmcnId" });
DropTable("dbo.Files");
}
}
但是当我做update-database 时,我得到一个错误:
Error Number:1776,State:0,Class:16
There are no primary or candidate keys in the referenced table 'dbo.AMCNs' that match the referencing column list in the foreign key 'FK_dbo.Files_dbo.AMCNs_AmcnId'.
Could not create constraint. See previous errors.
据我所知,实体框架应该能够弄清楚我希望 AmcnId 是指向 AMCN.Id 的外键。事实上,当我制作另一个课程 FoSL 时,它运行良好。
public class FoSL
{
public int Id { get; set; }
public int AmcnId { get; set; }
public string FO { get; set; }
public DateTime StartDate { get; set; }
public string Location { get; set; }
}
生成的迁移类
public partial class FoSL : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.FoSLs",
c => new
{
Id = c.Int(nullable: false, identity: true),
AmcnId = c.Int(nullable: false),
FO = c.String(),
StartDate = c.DateTime(nullable: false),
Location = c.String(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AMCNs", t => t.AmcnId, cascadeDelete: true)
.Index(t => t.AmcnId);
}
public override void Down()
{
DropForeignKey("dbo.FoSLs", "AmcnId", "dbo.AMCNs");
DropIndex("dbo.FoSLs", new[] { "AmcnId" });
DropTable("dbo.FoSLs");
}
}
我看不出FoSL 和File 类或它们的迁移之间有任何真正的区别。据我所知,这应该有效。那我做错了什么?
我尝试在AMCN.Id 上添加[Key],但没有帮助。
编辑:最初的 dbmigration 包括 Up():
CreateTable(
"dbo.AMCNs",
c => new
{
Id = c.Int(nullable: false, identity: true),
Created = c.DateTime(nullable: false),
//lots of other data here....
})
.PrimaryKey(t => t.Id);
【问题讨论】:
-
如果你不使用Fluent API配置,你必须正确使用ef code first conventions name。
-
导致错误的“AMCN”迁移类在哪里,您的错误说 AMCN 表没有主键..首先检查该代码
-
@KarthikGanesan 编辑了包含它的问题,M.Wiśnicki 不是吗?
-
迁移将在上下文创建之前更新数据库,懒惰的引导与该问题无关
-
在文件类 [ForeignKey("AMCN") 的 AmcnId 上键入此 arrtibute
标签: entity-framework sql-server-2008