okinawa

IT勉強メモ

コードファーストとDBファーストで外部キーの設定

 

コードファースト

※下記の方法だと上手く行かなかった

なので、直接DBで外部キーを設定

→モデルクラスを下記と同じように外部キー・ナビゲーションプロパティを追加(ナビゲーションプロパティはいらなかった気もする。よく覚えておらず)

→Add-migrationもupdate-databaseもやらずで完了

 

 

以下が、上手く行かなかった方法↓

・参考

public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
 
public List<Post> Posts { get; set; } //コレクションナビゲーションプロパティ
}
 
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
 
public int BlogId { get; set; } //外部キー
public Blog Blog { get; set; } // 参照ナビゲーションプロパティ
}
 
using Microsoft.EntityFrameworkCore.Migrations;
 
namespace CodeFirst.Migrations
{
public partial class Initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Blog",
columns: table => new
{
BlogId = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Url = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Blog", x => x.BlogId);
});
 
migrationBuilder.CreateTable(
name: "Post",
columns: table => new
{
PostId = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Title = table.Column<string>(type: "nvarchar(max)", nullable: true),
Content = table.Column<string>(type: "nvarchar(max)", nullable: true),
BlogId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Post", x => x.PostId);
table.ForeignKey(
name: "FK_Post_Blog_BlogId",
column: x => x.BlogId,
principalTable: "Blog",
principalColumn: "BlogId",
onDelete: ReferentialAction.Cascade);
});
 
migrationBuilder.CreateIndex(
name: "IX_Post_BlogId",
table: "Post",
column: "BlogId");
}
 
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Post");
 
migrationBuilder.DropTable(
name: "Blog");
}
}
}
 

DBファースト

SQLServerで外部キー設定してスキャフォールディングするとこんな感じになる。
・モデルクラス
public partial class Character
{
[Key]
public int CharacterId { get; set; }
public int TeamId { get; set; } // 外部キー
public string CharacterName { get; set; }
public virtual Team Team { get; set; } // virtual型?というのができる。
 
コンテキストクラス
こんな感じで、外部キーが設定される。
entity.HasOne(d => d.Team)
.WithMany(p => p.Characters)
.HasForeignKey(d => d.TeamId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FromFK_character_ToTeam");

 

外部キーを元にLinqでテーブル結合してみる

結合1
SQL感があってわかりやすい。
var query = from photo in context.Set<PersonPhoto>() //photo変数にPersonPhotoテーブルを代入
join person in context.Set<Person>() // person変数にPersonテーブルを代入
on photo.PersonPhotoId equals person.PhotoId // テーブル結合条件
select photo; // PersonPhotoテーブルの列を表示
return View(await query.ToListAsync());
 
結合2
Includeメソッド
なんと簡単ことよ・・・。
var codeFirstContext = _context.Post.Include(p => p.Blog); // IncludeでPostとBlogテーブル結合
return View(await codeFirstContext.ToListAsync());