【发布时间】:2014-01-01 11:09:49
【问题描述】:
我刚刚开始使用代码优先方法来创建数据库。我有以下 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 的关系。我用于此的 fluent 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 属性允许为空。所以我在 OnModelCreating 方法中使用了 HasOptional()。
谁能告诉我如何解决这个问题以及我在这里缺少什么?
【问题讨论】:
-
如果你说
HasOptional(a => a.TagTypes),你应该让外键TagTypeID可以为空。 -
TagTypeId 在 TagDatabase 中是可为空的类型。所以我使用了 HasOptional(a => a.TagTypes) 。这是否正确
-
您的财产不是。
TagDatabase的TagTypeID属性应该是int?而不是int。
标签: c# linq entity-framework