我有以下 SQL 表(为简单起见,删除了列):
create table dbo.Packs
(
Id int identity not null
constraint Packs_Id_PK primary key clustered (Id)
);
create table dbo.Files
(
Id int identity not null
constraint Files_Id_PK primary key clustered (Id),
PackId int not null
);
alter table dbo.Files
add constraint Files_PackId_FK foreign key (PackId) references dbo.Packs(Id) on delete cascade on update cascade;
然后我按如下方式创建了 Pocos:
public class Pack {
public Int32 Id { get; set; }
public virtual ICollection<File> Files { get; set; }
} // Pack
public class File {
public Int32 Id { get; set; }
public int PackId { get; set; }
public virtual Pack Pack { get; set; }
} // File
配置是:
internal class PackMapper : EntityTypeConfiguration<Pack> {
internal PackMapper()
: base() {
ToTable("Packs");
HasKey(x => x.Id);
Property(x => x.Id).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
} // PackMapper
internal class FileMapper : EntityTypeConfiguration<File> {
internal FileMapper()
: base() {
ToTable("Files");
HasKey(x => x.Id);
Property(x => x.Id).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
// 1 > CONFIGURATION WITH FK IN ENTITY
Property(x => x.PackId).HasColumnName("PackId").IsRequired();
HasRequired(x => x.Pack).WithMany(x => x.Files).HasForeignKey(x => x.PackId);
// 2 > CONFIGURATION WITHOUT FK IN ENTITY
// HasRequired<Pack>(x => x.Pack).WithMany(y => y.Files).Map(z => { z.MapKey("PackId"); });
}
} // FileMapper
然后我尝试删除一个文件:
Pack pack = context.Packs.First(x => x.Id == 31);
IList<Int32> ids = context.Entry<Pack>(pack).Collection(x => x.Files).Query().Select(x => x.Id).ToList();
foreach (int id in ids) {
File file = new File() { Id = id };
context.Files.Attach(file);
context.Files.Remove(file);
}
context.SaveChanges();
如果我使用配置 1,文件将被删除。
如果我使用配置 2(不需要 FK 属性),则会收到错误消息:
“Context.Files”中的实体参与“File_Pack”关系。找到 0 个相关的“File_Pack_Target”。1 'File_Pack_Target' 是预期的。
这是为什么?不定义 FK 属性时是否需要指定其他内容?
注意:我使用的是 EF 5。