INSERT 语句与实体框架中的 FOREIGN KEY 约束冲突
我有两个表 Subscription 和 PackageType。 Subs 将 FK 作为 PackageTypeId。现在,当我使用 EF 4.1 在订阅表中插入新记录时,它会引发异常
INSERT 语句与 FOREIGN KEY 约束“FK_Subscription_PaymentType”
冲突。冲突发生在数据库“MyDatabaseName”、表“dbo.PaymentType”
、列'Id'
中。 该声明已终止。
表信息为:
订阅表:
Id (PK)
PaymentTypeId (FK)
Period
date
PaymentType:
Id (PK)
Name
代码如下:
public void Proceed(SubscriptionSessionData data)
{
if (data != null)
{
PMSCatalogEntities entities = new PMSCatalogEntities();
Subscription subs = new Subscription();
subs.Id = Guid.NewGuid();
subs.ApplicableFrom = data.ApplicableFrom;
subs.TenantId = tenant.Id;
subs.PackageId = data.PaymentType;
subs.PaymentTypeId = data.PaymentType;
entities.AddToSubscriptions(subs);
entities.SaveChanges();
}
}
关于这个问题有什么想法吗?
I have two table Subscription and PackageType. Subs has FK as PackageTypeId. Now when I am inserting a new record in Subscription table using EF 4.1 it is throwing an exception
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Subscription_PaymentType"
. The conflict occurred in database "MyDatabaseName", table "dbo.PaymentType"
, column 'Id'
.
The statement has been terminated.
Tables information are:
Subscription Table:
Id (PK)
PaymentTypeId (FK)
Period
date
PaymentType:
Id (PK)
Name
And the Code is as given below:
public void Proceed(SubscriptionSessionData data)
{
if (data != null)
{
PMSCatalogEntities entities = new PMSCatalogEntities();
Subscription subs = new Subscription();
subs.Id = Guid.NewGuid();
subs.ApplicableFrom = data.ApplicableFrom;
subs.TenantId = tenant.Id;
subs.PackageId = data.PaymentType;
subs.PaymentTypeId = data.PaymentType;
entities.AddToSubscriptions(subs);
entities.SaveChanges();
}
}
Any idea about this issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我已经测试过这个场景,效果很好:
在数据库上,
我唯一需要确定的是,本例中 ID 为 1 的付款会保留在付款表上,而且它的工作原理就像一个魅力!
I have already tested this scenario and it works great:
And on the DB
The only thing I have to be sure is that a Payment with Id 1 for this example is persisted on the Payments table, and it works like a charm!!
我最近看到这一点,当关系一起使用父记录和子记录的主键,而不是主键和外键时。图表上有一条线索,因为基数是错误的(1->0.1 而不是 1->*)
I saw this recently when the relationship used the primary keys of the parent and child record together, instead of the primary key and foreign key. There was a clue on the diagram for this in that the cardinality was wrong (1->0.1 instead of 1 -> *)
您确定分配给 subs.PaymentTypeId (data.PaymentType) 的值是 PaymentType 表中现有记录的有效 ID 吗?
Are you sure that the value that you are assigning to subs.PaymentTypeId (data.PaymentType) is a valid Id from an existing record on the PaymentType table?
您正在尝试插入错误的引用表主键值,该值未在数据库中显示。
You are trying to insert a bad reference table primary key value, which is not presented in the database.