如何解决网络核心实体框架中的迁移冲突
我的 sql Server 数据库中有两个表 - 一个用于类别:
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }
[ForeignKey("ParentId")]
public Category Parent { get; set; }
}
然后是 Assistant
表:
public class Assistant
{
public int Id { get; set; }
public int UserId { get; set; }
public DateTime CreatedAtUtc { get; set; }
public Status Status { get; set; }
public int? CategoryId { get; set; }
[ForeignKey("CategoryId")]
public Category Category { get; set; }
}
当我尝试进行迁移时,出现此错误:
ALTER TABLE 语句与 FOREIGN KEY 约束“FK_Assistants_Categories_CategoryId”冲突。冲突发生在数据库“Pirma isMssql”,表“dbo.Categories”,列“Id”。
我不知道为什么。
谢谢
解决方法
修复您的课程:
public partial class Assistent
{
[Key]
public int Id { get; set; }
public int UserId { get; set; }
public User User{ get; set; }
public DateTime CreatedAtUtc { get; set; }
public int StatusId { get; set; }
public Status Status { get; set; }
public int? CategoryId { get; set; }
[ForeignKey(nameof(CategoryId))]
[InverseProperty("Assistents")]
public virtual Category Category { get; set; }
}
public partial class Category
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }
[ForeignKey(nameof(ParentId))]
[InverseProperty(nameof(Category.InverseParent))]
public virtual Category Parent { get; set; }
[InverseProperty(nameof(Assistent.Category))]
public virtual ICollection<Assistent> Assistents { get; set; }
[InverseProperty(nameof(Category.Parent))]
public virtual ICollection<Category> InverseParent { get; set; }
}
这是数据库上下文:
public partial class AssistentsContext : DbContext
{
public AssistentsContext()
{
}
public AssistentsContext(DbContextOptions<AssistentsContext> options)
: base(options)
{
}
public virtual DbSet<Assistent> Assistents { get; set; }
public virtual DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Assistent>(entity =>
{
entity.HasOne(d => d.Category)
.WithMany(p => p.Assistents)
.HasForeignKey(d => d.CategoryId);
});
modelBuilder.Entity<Category>(entity =>
{
entity.HasOne(d => d.Parent)
.WithMany(p => p.InverseParent)
.HasForeignKey(d => d.ParentId);
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。