![](/img/trans.png)
[英]The INSERT statement conflicted with the FOREIGN KEY constraint - Entity Framework
[英]The INSERT statement conflicted with the FOREIGN KEY constraint in Entity Framework
我有两个表Subscription和PackageType。 Subs具有FK作为PackageTypeId。 现在,当我使用EF 4.1在Subscription表中插入新记录时,它会引发异常
INSERT语句与FOREIGN KEY约束"FK_Subscription_PaymentType"
冲突。 数据库“ MyDatabaseName”的表"dbo.PaymentType"
列'Id'
发生了冲突。 该语句已终止。
表信息是:
订阅表:
Id (PK)
PaymentTypeId (FK)
Period
date
付款方式:
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();
}
}
关于这个问题有什么想法吗?
您试图插入错误的引用表主键值,该值未在数据库中显示。
最近,当关系使用父级和子级记录的主键而不是主键和外键时,我看到了这一点。 在图表上有一个线索,就是基数是错误的(1-> 0.1而不是1-> *)
您确定要分配给subs.PaymentTypeId(data.PaymentType)的值是来自PaymentType表上现有记录的有效ID吗?
我已经测试过这种情况,并且效果很好:
class Program
{
static void Main(string[] args)
{
PMSCatalogEntities entities = new PMSCatalogEntities();
Subscription subs = new Subscription();
subs.Id = Guid.NewGuid();
subs.Date = DateTime.Now;
subs.PaymentId = 1;
entities.Subscriptions.Add(subs);
entities.SaveChanges();
}
}
public class PMSCatalogEntities : DbContext
{
public DbSet<Subscription> Subscriptions { get; set; }
public DbSet<Payment> Payments { get; set; }
}
public class Subscription
{
public Guid Id { get; set; }
public DateTime Date { get; set; }
public Payment Payment { get; set; }
public int PaymentId { get; set; }
}
public class Payment
{
public int Id { get; set; }
public string Type { get; set; }
}
并在数据库上
TABLE [dbo].[Payments](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Type] [nvarchar](max) NULL,
TABLE [dbo].[Subscriptions](
[Id] [uniqueidentifier] NOT NULL,
[Date] [datetime] NOT NULL,
[PaymentId] [int] NOT NULL,
我唯一需要确定的是,此示例中的ID为1的Payments保留在Payments表上,并且它的作用就像是一个吊饰!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.