FileとAMCNの2つのモデルの間に一対多の関係を作成しようとしています。ここに私のファイルです:Entity Frameworkは「参照されたテーブルにプライマリキーまたは候補キーがありません...」
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を指す外部キーになるようにAmcnIdを設定する必要があります。実際、私が別のクラスの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);
あなたは流暢なAPIの設定を使用しない場合は、あなたが適切EFコード最初の規則名を使用する必要があります。 –
エラーの原因となっている「AMCN」のマイグレーションクラスは、AMCNテーブルにはプライマリキーがありません。そのコードを最初に確認してください –
@KarthikGanesanは質問を編集しました、M.Wiśnickiは私ですか? –