여기에도 이와 비슷한 질문이 몇 개 있지만 간략한 시나리오에서 누락 된 부분을 확인하는 데 문제가 있습니다.Entity Framework 6 : 코드 첫 번째 계단식 삭제
의 내가 영리하게 자신의 이름을 딴, 다음과 같은 테이블이 있다고 가정 해 봅시다 : 결과 클래스와
'JohnsParentTable' (Id, Description)
'JohnsChildTable' (Id, JohnsParentTableId, Description)
내가 부모 테이블의 행에이 데이터베이스에 너무
public class JohnsParentTable
{
public int Id { get; set; }
public string Description { get; set; }
public virtual ICollection<JohnsChildTable> JohnsChildTable { get; set; }
public JohnsParentTable()
{
JohnsChildTable = new List<JohnsChildTable>();
}
}
internal class JohnsParentTableConfiguration : EntityTypeConfiguration<JohnsParentTable>
{
public JohnsParentTableConfiguration()
{
ToTable("dbo.JohnsParentTable");
HasKey(x => x.Id);
Property(x => x.Id).HasColumnName("Id").IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.Description).HasColumnName("Description").IsRequired().HasMaxLength(50);
}
}
public class JohnsChildTable
{
public int Id { get; set; }
public string Description { get; set; }
public int JohnsParentTableId { get; set; }
public JohnsParentTable JohnsParentTable { get; set; }
}
internal class JohnsChildTableConfiguration : EntityTypeConfiguration<JohnsChildTable>
{
public JohnsChildTableConfiguration()
{
ToTable("dbo.JohnsChildTable");
HasKey(x => x.Id);
Property(x => x.Id).HasColumnName("Id").IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.Description).HasColumnName("Description").IsRequired().HasMaxLength(50);
HasRequired(a => a.JohnsParentTable).WithMany(c => c.JohnsChildTable).HasForeignKey(a => a.JohnsParentTableId);
}
}
처럼 보이는 이 부모에 연결된 자식 테이블의 두 행과 함께 1의 ID. 내가 이렇게하면 :
var parent = db.JohnsParentTable.FirstOrDefault(a => a.Id == 1)
개체가 올바르게 채워집니다. 나는이 행을 삭제하려고 경우 :
는var parent = new Data.Models.JohnsParentTable() { Id = 1 };
db.JohnsParentTable.Attach(parent);
db.JohnsParentTable.Remove(parent);
db.SaveChanges();
엔티티 프레임 워크는 다음 실행을 시도 :
DELETE [dbo].[JohnsParentTable]
WHERE ([Id] = @0)
-- @0: '1' (Type = Int32)
-- Executing at 1/23/2014 10:34:01 AM -06:00
-- Failed in 103 ms with error: The DELETE statement conflicted with the REFERENCE constraint "FK_JohnsChildTable_JohnsParentTable". The conflict occurred in database "mydatabase", table "dbo.JohnsChildTable", column 'JohnsParentTableId'.
The statement has been terminated.
내 질문은 정확히 내가 엔티티 프레임 워크가 삭제해야 함을 알 수 있도록 실종 누구인지 부모를 삭제하기 전에 'JohnsChildTable'행을 삭제 하시겠습니까?
영업 문제는 코드 첫 번째입니다. 이 솔루션은 Model First에만 적합합니다. – vidalsasoon