[Solved] Always Foreign Key violation - What's wrong?

Discussion of open issues, suggestions and bugs regarding Entity Developer - ORM modeling and code generation tool
Post Reply
PixelHunter
Posts: 8
Joined: Thu 29 Jun 2017 11:07

[Solved] Always Foreign Key violation - What's wrong?

Post by PixelHunter » Fri 21 Jul 2017 13:08

I have a very simple model:
Image

I generated the code with the DbContext template version 6.1.299

When I try to insert data with

Code: Select all

            
var context = new Entities.Entities();

var kunde = new Kunde()
{
    Id = Guid.NewGuid(),
    Nr = 1,
    Name = "John Smith",
    Created = DateTime.Now
};

context.BaseClass.Add(kunde);
context.SaveChanges();

var adresse = new Adresse()
{
   Id = Guid.NewGuid(),
   Kunde = kunde,
   KundeId = kunde.Id,
   Strasse = "Main road 15",
   PLZ = "20095",
   Ort = "City",
   Created = DateTime.Now
};

context.BaseClass.Add(adresse);
context.SaveChanges();
The kunde object is saved successful, but the adress SaveChange() always throws an error: INSERT fails, with Foreign Key violation on FK_dbo.Adressen_dbo.Kunde_Id'. Conflict on table 'dbo.Kunde', column 'Id'

What's wrong please?
Last edited by PixelHunter on Sat 22 Jul 2017 15:25, edited 1 time in total.

PixelHunter
Posts: 8
Joined: Thu 29 Jun 2017 11:07

Re: Always Foreign Key violation - What's wrong?

Post by PixelHunter » Sat 22 Jul 2017 08:16

I tried a INSERT directly to the database

Code: Select all

INSERT INTO Adresse VALUES (NEWID(), 'Main Road 15', '20095', 'Hamburg','{FE5852D8-393A-4DEF-850F-50DEC50EEAE2}', GETDATE())
Same error.

Now I investigated the created Foreign Keys. There are two on the table [Adresse]. The first maps [Adresse].[KundeId] to [Kunde].[Id] and the second maps [Adresse].[Id] with [Kunde].[Id] which does not make sense.

Why this second FK is created?

Here are the three config files created:

BaseClassConfiguration.cs

Code: Select all

//------------------------------------------------------------------------------
// This is auto-generated code.
//------------------------------------------------------------------------------
// This code was generated by Devart Entity Developer tool using Entity Framework DbContext template.
// Code is generated on: 22.07.2017 09:52:42
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//------------------------------------------------------------------------------

using System.Data.Entity.ModelConfiguration;

namespace Entities.Mapping
{

    public partial class BaseClassConfiguration : EntityTypeConfiguration<BaseClass>
    {

        public BaseClassConfiguration()
        {
            this
                .HasKey(p => p.Id)
                .Map(tpc => { });
            // Properties:
            this
                .Property(p => p.Id)
                    .IsRequired()
                    .HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None);
            OnCreated();
        }

        partial void OnCreated();

    }
}
KundeConfiguration.cs

Code: Select all

//------------------------------------------------------------------------------
// This is auto-generated code.
//------------------------------------------------------------------------------
// This code was generated by Devart Entity Developer tool using Entity Framework DbContext template.
// Code is generated on: 22.07.2017 09:52:42
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//------------------------------------------------------------------------------

using System.Data.Entity.ModelConfiguration;

namespace Entities.Mapping
{

    public partial class KundeConfiguration : EntityTypeConfiguration<Kunde>
    {

        public KundeConfiguration()
        {
            this
                .Map(tpc =>
                {
                    tpc.MapInheritedProperties();
                    tpc.ToTable("Kunde", "dbo");
                });
            // Properties:
            this
                .Property(p => p.Nr)
                    .HasColumnType("int");
            this
                .Property(p => p.Name)
                    .HasMaxLength(32)
                    .HasColumnType("varchar");
            // Association:
            this
                .HasMany(p => p.Adressen)
                    .WithOptional(c => c.Kunde)
                .HasForeignKey(p => p.KundeId)
                    .WillCascadeOnDelete(false);
            OnCreated();
        }

        partial void OnCreated();

    }
}
AdresseConfiguration.cs

Code: Select all

//------------------------------------------------------------------------------
// This is auto-generated code.
//------------------------------------------------------------------------------
// This code was generated by Devart Entity Developer tool using Entity Framework DbContext template.
// Code is generated on: 22.07.2017 09:52:42
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//------------------------------------------------------------------------------

using System.Data.Entity.ModelConfiguration;

namespace Entities.Mapping
{

    public partial class AdresseConfiguration : EntityTypeConfiguration<Adresse>
    {

        public AdresseConfiguration()
        {
            this
                .Map(tpc =>
                {
                    tpc.MapInheritedProperties();
                    tpc.ToTable("Adresse", "dbo");
                });
            // Properties:
            this
                .Property(p => p.Strasse)
                    .HasMaxLength(32)
                    .HasColumnType("varchar");
            this
                .Property(p => p.PLZ)
                    .HasMaxLength(6)
                    .HasColumnType("varchar");
            this
                .Property(p => p.Ort)
                    .HasMaxLength(32)
                    .HasColumnType("varchar");
            this
                .Property(p => p.KundeId)
                    .HasColumnType("uniqueidentifier");
            OnCreated();
        }

        partial void OnCreated();

    }
}
What I am doing wrong, where is the reason to create this weired FK or how I can avoid it?
Why a BaseClassConfig is created? I do not want this, the inheritance modifier is 'abstract'.

I cannot find my mistake.

PixelHunter
Posts: 8
Joined: Thu 29 Jun 2017 11:07

Re: Always Foreign Key violation - What's wrong?

Post by PixelHunter » Sat 22 Jul 2017 15:24

After a deep research I found the problem myself:

The problem was, that I renamed the table Adresse from Adressen in an early stage.

The automatic created db migration code does only rename the tables but not the foreign keys.

Later when I change associations it tries to drop the foreign keys with the old name 'Adressen' but no not 'Adresse' and does not show any errors during this process, it just leave these false FKs.

So I learned: Do not change any table names or check any dependend indexes or other constraints.

Sorry for bothering you with my learnings, but maybe it will help some other newbies as it is.

Shalex
Site Admin
Posts: 8247
Joined: Thu 14 Aug 2008 12:44

Re: [Solved] Always Foreign Key violation - What's wrong?

Post by Shalex » Mon 24 Jul 2017 07:25

Thank you for confirming a fix.

Post Reply