// 这个是出问题的实体 public class PClazz : AggregateRoot { [Required] public string Name { get; set; } public string Descript { get; set; } public DateTime CreateTime { get; set; } public int? Top { get; set; } public virtual PClazz Parent { get; set; } public virtual List<PClazz> Chile { get; set; } } //Map定义 public class PClazzMap : EntityTypeConfiguration<PClazz> { public PClazzMap() { this.HasKey(p => p.ID); this.ToTable("P_ProductClazz"); this.HasOptional(p => p.Parent) .WithMany(p => p.Chile) .HasForeignKey(p => p.Top) .WillCascadeOnDelete(false); } }
var urep = new Buybate.Domain.Repositories.PClazzRepository(); var user = new Domain.Entity.PClazz(); user.CreateTime = DateTime.Now; user.Descript = Stupid.Common.CodeCommon.CreateCode(Stupid.Common.CodeCommon.CodeType.Chinese, ran.Next(0, 150)); user.Name = Stupid.Common.CodeCommon.CreateCode(Stupid.Common.CodeCommon.CodeType.Chinese, ran.Next(0, 150)); urep.Insert(user); urep.SaveChange(); //这只是个测试,在SaveChange出错报异常: $exception {"“xxxx.PClazz”中的实体参与“Product_Clazz”关系。找到 0 个相关的“Product_Clazz_Source”。应有 1 个“Product_Clazz_Source”。"} System.Data.Entity.Infrastructure.DbUpdateException
现在是不会有异常的
//实体 public class BlogClazz :AggregateRoot { /// <summary> /// 类别名称 /// </summary> [Required] public string CName { get; set; } /// <summary> /// 上一级ID /// </summary> public int? Top { get; set; } /// <summary> /// 层次ID /// </summary> public int Deep { get; set; } /// <summary> /// 添加时间 /// </summary> public DateTime AddTime { get; set; } /// <summary> /// 类别描述 /// </summary> public string Describe { get; set; } public virtual BlogClazz Parent { get; set; } public virtual List<BlogClazz> BlogCList { get; set; } } //Map public class BlogClazzMap : EntityTypeConfiguration<BlogClazz> { public BlogClazzMap() { this.HasKey(p => p.ID); this.ToTable("M_BlogClazz"); this.HasOptional(p => p.Parent) .WithMany(p => p.BlogCList) .HasForeignKey(p => p.Top) .WillCascadeOnDelete(false); } } //测试添加 var blo = new Domain.Repositories.BlogClazzRepository(); Domain.Entity.BlogClazz bcl = new Domain.Entity.BlogClazz(); bcl.AddTime = DateTime.Now; bcl.CName = Stupid.Common.CodeCommon.CreateCode(Stupid.Common.CodeCommon.CodeType.Chinese); bcl.Deep = 1; bcl.Describe = Stupid.Common.CodeCommon.CreateCode(Stupid.Common.CodeCommon.CodeType.Chinese); blo.Insert(bcl); blo.SaveChange();
求大神解答
这个是数据库结构
这个错误是由于自己没认真思考。异常报的是PClazz与Product的关系异常。
但是为什么会有这个异常的我还是要好好找一找原因。