Programming

ReferentialConstraint의 종속 속성은 저장소 생성 열에 매핑됩니다.

procodes 2020. 8. 27. 22:26
반응형

ReferentialConstraint의 종속 속성은 저장소 생성 열에 매핑됩니다.


데이터베이스에 쓸 때이 오류가 발생합니다.

ReferentialConstraint의 종속 속성은 저장소 생성 열에 매핑됩니다. 열 : '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;
    }

스키마는 다음과 같습니다.

여기에 이미지 설명 입력


테이블간에 잘못된 열 관계를 정의했을 수 있습니까? 다른 열과 하나는 자동 숫자로 설정되었습니다.

나에게 일어난 일입니다.


이 오류는 지원되지 않는 관계를 사용 중이거나 매핑에 오류가 있음을 나타냅니다. 귀하의 코드는 아마도 오류와 절대적으로 관련이 없습니다.

이 오류는 종속 엔터티의 외래 키 속성이 저장소 생성으로 정의 된 엔터티간에 일부 관계가 있음을 의미합니다. 저장소 생성 속성은 데이터베이스에 채워집니다. EF는 저장소 생성 속성을 외래 키 (기본 키의 계산 된 속성)로 지원하지 않습니다.


나는 같은 문제가 있었다. 여기에 제공된 답변을 바탕으로 추적하고 해결할 수 있었지만 아래에 설명 된 이상한 문제가있었습니다. 나중에 누군가에게 도움이 될 수 있습니다.

내 종속 테이블에서 외래 키 열이 StoreGeneratedPattern = "Identity"로 설정되었습니다. "없음"으로 변경해야했습니다. 불행히도 디자이너 내부에서 그렇게하는 것은 전혀 작동하지 않았습니다.

디자이너가 생성 한 XML (SSDL)을 살펴 보았는데 이러한 속성이 여전히 존재하므로 수동으로 제거했습니다. 또한 데이터베이스의 열을 수정해야했습니다 (CREATE TABLE SQL에서 Identity (1,1) 제거)

그 후 문제가 사라졌습니다.


나는 같은 문제가 있었고 SQL Server에서 테이블 디자인을 파헤친 후 실수로 테이블의 기본 키를 외래 키로 설정했다는 사실을 발견했습니다.

SQL 서버 테이블 디자인 흐름

이 이미지에서 JobID가 테이블의 기본 키이지만 실수로 외래 키임을 알 수 있습니다.


Payment와 다른 테이블 / 엔터티 간의 관계를 다시 확인하십시오. 문제가 숨겨져있을 가능성이 가장 높기 때문에 PaymentId를 포함하지 않아야하는 항목을 포함합니다.

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!


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 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


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

참고URL : https://stackoverflow.com/questions/6384659/a-dependent-property-in-a-referentialconstraint-is-mapped-to-a-store-generated-c

반응형