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?
I have already tested this scenario and it works great:
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; }
}
And on the DB
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,
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!!
You are trying to insert a bad reference table primary key value, which is not presented in the database.