ReferentialConstraint 中的依赖属性映射到存储生成的列

写入数据库时出现这个错误:

ReferentialConstraint 中的依赖属性映射到 Store 生成的列。列: ‘ PaymentId’。

public bool PayForItem(int terminalId, double paymentAmount,
eNums.MasterCategoryEnum  mastercategoryEnum, int CategoryId, int CategoryItemId)
{


using (var dbEntities = new DatabaseAccess.Schema.EntityModel())
{
int pinnumber = 0;
long pinid = 1; //getPinId(terminalId,ref pinnumber) ;
var payment = new DatabaseAccess.Schema.Payment();
payment.CategoryId = CategoryId;
payment.ItemCategoryId = CategoryItemId;
payment.PaymentAmount = (decimal)paymentAmount;
payment.TerminalId = terminalId;
payment.PinId = pinid;


payment.HSBCResponseCode = "";
payment.DateActivated = DateTime.Now;
payment.PaymentString = "Payment";
payment.PromotionalOfferId = 1;
payment.PaymentStatusId = (int)eNums.PaymentStatus.Paid;


//payment.PaymentId = 1;


dbEntities.AddToPayments(payment);
dbEntities.SaveChanges();
}
return true;
}

模式是:

enter image description here

86905 次浏览

This error says that you are using unsupported relation or you have error in your mapping. Your code is most probably absolutely unrelated to the error.

The error means that you have some relation between entities where foreign key property in dependent entity is defined as store generated. Store generated properties are filled in the database. EF doesn't support store generated properties as foreign keys (as well as computed properties in primary keys).

Is it possible that you defined a bad column relation between your tables?

In my case, I had different columns and one was set as autonumeric.

I had the same problem. Based on the answers provided here I was able to track it and solve it, but I had a strange issue described below - it might help somebody in the future.

On my dependent tables, the foreign Key columns have been set to StoreGeneratedPattern="Identity". I had to change it to "None". Unfortunately, doing so inside designer didn't work at all.

I looked in the designer-generated XML (SSDL) and these properties were still there so I removed them manually. I also had to fix the columns on the database (remove the Identity(1,1) from CREATE TABLE SQL)

After that, the problem went away.

Re-check the relationship between Payment and the other tables/entities. Including the ones that shouldn't contain PaymentId because that's where the problem is most likely hiding.

When creating foreign keys in SQL Server Management Studio, the primary key is defaulted, and this default is reverted when the parent table is changed, so be careful to change values in the correct order in the "Tables and Columns" window.

Also, after you've fixed the problematic relationship, there's a good chance that a simple "Refresh" on the model won't correctly remove the erronous relationship from the model and you'll get the same error even after the "fix", so do this yourself in the model before performing a refresh. (I found this out the hard way.)

If you have checked your relationships and are good there.

Delete the table in the edmx and then update from database. This will save you doing the update manually.

For me it was a wrongly placed foreign key in the table but even after altering the table to fix it, it was still not working. You need to update the EDMX files (and not enough to "refresh" the table from the model, you need to remove and add the table again in the model).

In addition to the accepted answer, if you are using EF Reverse POCO generator or some other tool that generates your POCO's, make sure you regenerate them!

I had the same problem and after some digging in table design in sql server , I found that mistakenly i set table's primary key also as foreign key.

sql server table design flow

In this image you can see that JobID is table's primary key but also mistakenly foreign key.

In my case the problem was caused by having a two-way 1-1 relationship:

class Foo{
[Key]
Id
[ForeignKey]
BarId
...
}
class Bar{
[Key]
Id
[ForeignKey]
FooId
...
}

I had to simply remove one of the two foreign keys (not necessary anyway).

In my case it was simply that I did not have permissions set properly on the database. I had read only set and Entity framework was giving me a ReferentialConstraint error which threw me off. Added additional write permissions and all was well.

In my case, I had a Database Generated property, and a ForeignKey navigation property set up to reference a 1 to 1 related table.

This wasn't something I could remove, I needed to be able to both set the primary key of the entity to be Database Generated AND I needed to be able to reference the 1 to 1 table as a navigation property.

Not sure if this is the same for others, but this problem was only showing up when creating a new entity, reading or editing existing entities did not exhibit the issue, so I got around the issue by creating an inherited version of my Context and using the Fluent method to switch off the navigation property when creating.

So, my original entity looked like this:

public partial class MyEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid id{ get; set; }




// Navigation
[ForeignKey("id")]
public PathEntity Path { get; set; }
}

So I made a special inherited context that looked like this:

    private class _navPropInhibitingContext : EF.ApplicationDBContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);


modelBuilder.Entity<MyEntity>()
.Ignore(e => e.Path);


}
}

and then changed the code that created the new entity to make user of the new context type

    using (var specialContext = new _navPropInhibitingContext())
{
var dbModel = new MyEntity()
{
...
};


specialContext.MyEntity.Add(dbModel);
await specialContext.SaveChangesAsync();
}

Hope this helps somebody

My problem was caused by redundant defining of the Primary key in the configuration.

this
.Property(p => p.Id)
.HasColumnName(@"id")
.IsRequired()
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity) // this is redundant when you want to configure a One-to-Zero-or-One relationship
.HasColumnType("int");

Remove this line

.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)


Example http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx

This is enough to define the relationship

// Configure Student & StudentAddress entity
modelBuilder.Entity<Student>()
.HasOptional(s => s.Address) // Mark Address property optional in Student entity
.WithRequired(ad => ad.Student); // mark Student property as required in StudentAddress entity. Cannot save StudentAddress without Student

In my case Id field wich FK just in Entity Framework the propierty "StoreGeneratedPattern" was set "Itentity" instead of "None"

I have the same issue.

Here is my case, if you are adding a new record and has a primary key but is not auto-incremented, this will trigger an error.

I thought first that it will automatically generate the key for me so I leave the Id as blank.

Example:

Customer cust = new Customer();
//cust.Id - I left it blank
db.Customer.Add(cust);
db.SaveChanges();

But upon quick investigation, I forgot to set it's Identity to true and that would trigger an error once you do SaveChanges on your DbContext.

So make sure if your Identity is true or not.

In my case I was passing auto generated primary key of the same table in foreign key column so entity frame work is throwing an error that it can not set a value of that column which is not generated yet as we can only get autogenerated value after save change

Bonus Request Id is my primary key

Here BonusRequestId is my primary key which I was doing a mistake

Correct Foreign Key