1
我有麻煩了如下描述:關係和外鍵錯誤與實體框架4.1
One or more validation errors were detected during model generation:
System.Data.Edm.EdmAssociationType: : Multiplicity conflicts with the referential constraint in Role 'CorpQuestionA_CorpQAnswer_Source' in relationship 'CorpQuestionA_CorpQAnswer'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.
我的屏幕截圖PIC數據庫:
和實體限定:
public class CorpQuestionA
{
[Key]
public Guid cqua_QuestionId { get; set; }
public Guid cqua_CorpId { get; set; }
[MaxLength]
public string cqua_Question { get; set; }
public DateTime cqua_Date { get; set; }
public Boolean cqua_IsAnswer { get; set; }
[ForeignKey("cqua_CorpId")]
public virtual CorpRegInfo510112 CorpRegInfo510112 { get; set; }
public virtual CorpQAnswer CorpQAnswer { get; set; }
}
public class CorpQAnswer
{
[Key]
public Guid cqan_QuestionId { get; set; }
public string cqan_Answer { get; set; }
[ForeignKey("cqan_QuestionId")]
public virtual CorpQuestionA CorpQuestionA { get; set; }
}
然後是ProjectDataEntities文件:
public class ProjectDataEntities : DbContext
{
public DbSet<CorpQuestionA> Tbl_CorpQuestionAs { get; set; }
public DbSet<CorpQAnswer> Tbl_CorpQAnswers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
modelBuilder.Entity<CorpQuestionA>().ToTable("tbl_CorpQuestionA");
modelBuilder.Entity<CorpQAnswer>().ToTable("tbl_CorpQAnswer");
//Todo: Add custom mapping rules here...
modelBuilder.Entity<CorpQuestionA>().HasOptional(p => p.CorpQAnswer).WithOptionalPrincipal(x => x.CorpQuestionA);//.Map(p => p.MapKey("cqua_QuestionId"));
}
}
當我做更新操作,它拋出一個異常,因爲描述之前
public bool AnswerCorpQuestion(AnswerCorpQuestionModel acqModel)
{
var prjPO = new ProjectDataEntities();
//update table CorpQuestionA
CorpQuestionA cqaModel0 = prjPO.Tbl_CorpQuestionAs.Find(acqModel.cqua_QuestionId);
cqaModel0.cqua_IsAnswer = acqModel.cqua_IsAnswer;
//insert table CorpQAnswer
CorpQAnswer cqaModel1 = new CorpQAnswer
{
cqan_QuestionId = acqModel.cqua_QuestionId,
cqan_Answer=acqModel.cqan_Answer
};
prjPO.Tbl_CorpQAnswers.Add(cqaModel1);
try
{
prjPO.SaveChanges();
return true;
}
catch(DbEntityValidationException dbEx)
{
throw dbEx;
}
}
等待幫助,THX
嘗試'modelBuilder.Entity()HasOptional(p值=> p.CorpQAnswer).WithRequired(X => x.CorpQuestionA);'在'OnModelCreating'方法,而不是'模型構建器。 Entity ()。HasOptional(p => p.CorpQAnswer).WithOptionalPrincipal(x => x.CorpQuestionA);' –
Eranga
非常感謝。如何選擇你的文章作爲正確答案? – richard20427176
我添加了評論作爲答案。你可以接受:) – Eranga