從 [EF] 學校範例資料庫 內可以看出,Person 和 StudentGrade 是 1 對 多關係,就拿它當範例來使用
C# Code 測試
using EFIdentity.Models;
namespace EFIdentity
{
class Program
{
static void Main(string[] args)
{
using (SchoolContext context = new SchoolContext())
{
// Add() 多載可以回傳 TEntity
var p = context.Person.Add(new Person() { LastName = "Identity", FirstName = "demo", EnrollmentDate = DateTime.Today, Discriminator = "Student" });
// StudentGrade.StudentID 直接設定 Person.Add() 回傳的 TEntity.PersonID
context.StudentGrade.Add(new StudentGrade() { StudentID = p.PersonID, CourseID = 4022, Grade = 3 });
context.StudentGrade.Add(new StudentGrade() { StudentID = p.PersonID, CourseID = 4041, Grade = 4 });
context.StudentGrade.Add(new StudentGrade()
{
StudentID = p.PersonID,
CourseID = 4061,
Grade = 5
});
// 透過 SaveChange() 進行資料儲存
context.SaveChanges();
}
}
}
}
從 SSMS 內去查詢結果從 SQL Profile 去側錄產生的 TSQL 語法,事後才想說要觀察 TSQL,所以和上圖的 identity 不同
exec sp_executesql N'INSERT [dbo].[StudentGrade]([CourseID], [StudentID], [Grade])
VALUES (@0, @1, @2)
SELECT [EnrollmentID]
FROM [dbo].[StudentGrade]
WHERE @@ROWCOUNT > 0 AND [EnrollmentID] = scope_identity()',N'@0 int,@1 int,@2 decimal(3,2)',@0=4022,@1=1068,@2=3.00
沒有留言:
張貼留言