【发布时间】:2018-01-19 16:40:47
【问题描述】:
我正在使用 Entity Framework 6 Code First
我有一个带有其他 2 个表的属性表,可能或可能不包含有关该属性的更多信息。
所以,换句话说。我可能只想将数据添加到属性表。
这是我的桌子模型:
public class PropertyForSale
{
[Key]
public int Id { get; set; }
[Index("IX_pid", IsClustered = false, IsUnique = true, Order = 1), MaxLength(128)]
public string pid { get; set; }
public string Test { get; set; }
[ForeignKey("pid")]
public virtual PropertyForSale_Predictions PropertyForSale_Predictions { get; set; }
[ForeignKey("pid")]
public virtual PropertyForSale_Ratios PropertyForSale_Ratios { get; set; }
}
public class PropertyForSale_Predictions
{
[Key, MaxLength(128)]
public string pid { get; set; }
public string Test { get; set; }
}
public class PropertyForSale_Ratios
{
[Key, MaxLength(128)]
public string pid { get; set; }
public string Test { get; set; }
}
其中,视觉上看起来像这样:
当我尝试使用此代码向属性表添加信息时:
using (Model1 db = new Model1())
{
db.PropertyForSale.Add(new Model.PropertyForSale
{
pid = "123",
Test = "Test"
});
db.SaveChanges();
}
我收到此错误:
MySqlException: 无法添加或更新子行:外键约束失败 ("efcodefirstmysql"."propertyforsale", CONSTRAINT "FK_PropertyForSale_PropertyForSale_Predictions_pid" FOREIGN KEY ("pid") REFERENCES "propertyforsale_predictions" ("pid"))
我不知道如何指定外键,以便在其他 2 个表中添加属性数据没有数据?
【问题讨论】:
-
如果您确实需要使用此设置,请不要指定这些外键中的任何一个。数据库服务器不能强制执行诸如“必须在某处......”之类的约束,所以不要告诉它这样做。
-
@tgz 但是当我调用数据时我不会有导航属性?喜欢 .Include("PropertyForSale_Predictions")?
-
你试过去掉 ForeignKey 注释并使用 id 字段吗?看起来有点脏,但您并没有那样添加约束,我相信您的导航属性应该仍然没问题
-
刚刚尝试删除 ForeignKey 注释,我得到了同样的错误:(
-
数据库正在强制执行已经存在的约束,您应该从数据库中的表中删除外键。我会说只需使用更新的架构运行新的迁移。
标签: c# entity-framework ef-code-first