我刚开始使用Code first方法来创建数据库。我有以下3个表:
public class TagDatabase
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int TagID { get; set; }
public string TagName { get; set; }
public string Description { get; set; }
public int Count { get; set; }
[ForeignKey("TagTypes")]
public virtual int TagTypeID { get; set; }
public virtual ICollection<TagTypesDb> TagTypes { get; set; }
[ForeignKey("Users")]
public virtual int CreatedBy { get; set; }
public virtual UsersDb Users { get; set; }
}
public class TagTypesDb
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int TagTypeID { get; set; }
public string TagTypeName { get; set; }
}
public class UsersDb
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserID { get; set; }
public string UserName { get; set; }
}
这里TagDatabse和User和TagType有1对1的重播。我用于此的流畅API代码是:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<TagDatabase>()
.HasOptional(a => a.TagTypes)
.WithMany()
.HasForeignKey(u => u.TagTypeID);
modelBuilder.Entity<TagDatabase>()
.HasRequired(a => a.Users)
.WithMany()
.HasForeignKey(u => u.CreatedBy);
}
现在我的问题是每当我尝试在TagDatabase中插入数据时,我都遇到了这个例外:
TagDatabase_TagTypes: : Multiplicity conflicts with the referential constraint in Role 'TagDatabase_TagTypes_Target' in relationship 'TagDatabase_TagTypes'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.
TagTypeId属性允许为null。因此我在OnModelCreating方法中使用了HasOptional()。
Cananybody请告诉我如何解决这个问题以及我在这里缺少什么?
答案 0 :(得分:0)
如果对应关系是可选的,则应该创建外键属性nullable
。
public class TagDatabase
{
//sniff...
[ForeignKey("TagTypes")]
public virtual int? TagTypeID { get; set; } //Since TagTypes is optional, this should be nullable
public virtual ICollection<TagTypesDb> TagTypes { get; set; }
//sniff...
}