我正在尝试指定列名以将“外键”映射到使用Fluent API.我正在连接到sql Express的一个实例.我搜索过Stack Overflow和Google,但许多不同的配置示例给了我相同的结果.
产品类别
public class Product { public int ProductId { get; set; } public string Name { get; set; } public int? ParentId { get; set; } public virtual Product ParentProduct { get; set; } public virtual ICollection<Product> ChildProducts { get; set; } }
产品映射到实体框架
public class ProductMap : EntityTypeConfiguration<Product> { public ProductMap() { HasKey(p => p.ProductId); Property(p => p.Name) .Isrequired(); // Self referencing foreign key association Property(c => c.ParentId) .IsOptional(); HasMany(c => c.ChildProducts) .WithOptional(c => c.ParentProduct) .HasForeignKey(c => c.ParentId); } }
问题
当我运行程序并且EF创建数据库时,结果是ParentID列出现NULL并且它创建了一个名为ParentProduct_ProductId的列.此列包含ParentId的正确值.
解决方法
尝试此解决方案:
public class ProductMap : EntityTypeConfiguration<Product> { public ProductMap() { HasKey(p => p.ProductId); Property(p => p.Name) .Isrequired(); // Self referencing foreign key association Property(c => c.ParentId) .IsOptional(); HasOptional(x => x.Parent) .WithMany(x => x.ChildProducts) .HasForeignKey(x => x.ParentId) .WillCascadeOnDelete(false); } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。