Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7616583
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T02:55:29+00:00 2026-05-31T02:55:29+00:00

I’m new to EF and have read some Tutorials and Googled many days to

  • 0

I’m new to EF and have read some Tutorials and Googled many days to find a solution for my problem. Sorry my english is not the best but i want try to formulate my Question.

Data Model

My Model created from SQL Express Database (shrinked Version to better Understand) :

See Image:

Create Sample Data

Now i try to fill my DB with Demo Data. I create an Object of Liegenschaft and fill data in this. Simple Version to show my Tree of Data (real Version can have many Object of HAUS in ObjektMenge=List and for ObjektMenge=List too.

List<Liegenschaft> LL = new List<Liegenschaft>(); 

        for (int i = 0; i < 2; i++)
        {
            Liegenschaft L = new Liegenschaft()
            {
                Strasse = "demostreet1",
                HausMenge = new List<Haus>(){ 
                new Haus(){ 
                    Nummer = 21, 
                    ObjektMenge = new List<Objekt>(){
                        new Objekt(){ 
                            Zimmer = 221,
                            MieterMenge= new List<Mieter>(){
                                new Mieter(){
                                    Name="DemoName",
                                    MietzinsMenge= new List<Mietzins>(){
                                        new Mietzins(){
                                            StartDate=System.DateTime.Now,
                                            EndDate=System.DateTime.Now},
                                        new Mietzins(){
                                            StartDate=System.DateTime.Now,
                                            EndDate=System.DateTime.Now}
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            };
         LL.Add(L);
        }

Try to save to DB

foreach (Liegenschaft Lieg in LL)
{
    using (var db = new ImmoReportsEntities())
    {
        db.Liegenschaft.Add(Lieg);
        db.SaveChanges();
    }  
 }

Problem

All of my Demo Data can be saved to Database and all FK’s are automatically correct created when the MietzinsMenge are NOT Filled!

If i have Data in This MietzinsMenge gives an error: FK_Mietzins_Objekt has identical Primary Key!

Info

I don’t use Forms to insert Data to this Tabel’s all Data come from another (external) DB and i want to import this to my DB. How can i import this MietZins too in my Data Tree and have all of this FK (LiegenschftId, ObjektId, MieterId).

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T02:55:30+00:00Added an answer on May 31, 2026 at 2:55 am

    It doesn’t look like you are setting primary key values for your Mietzins objects. You need to either set the primary key values before trying to save to the database or tell EF that the primary keys will be generated by the database.

    How you specify that the key is generated by the database depends on whether you are using Code First or Database First. In Code First, it’s usualy on by default for integer key types, or you can use the DatabaseGeneratedAttribute and set Identity. For Database First, you use the EF Designer and set the StoreGenerated facet of the key property to Identity.

    I re-created your model as shown in the diagram using the following classes and Code First mappings. (I recognize that you are probably not using Code First, but this was the easiest way for me to create the same model with all the relationships as shown in the diagram.)

    public class Mietzins
    {
        public int Id { get; set; }
        public int LiegenschaftId { get; set; }
        public int MieterId { get; set; }
        public int ObjektId { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
    
        public Liegenschaft Liegenschaft { get; set; }
        public Mieter Mieter { get; set; }
        public Objekt Objekt { get; set; }
    }
    
    public class Mieter
    {
        public int Id { get; set; }
        public int LiegenschaftId { get; set; }
        public int ObjektId { get; set; }
        public string Name { get; set; }
    
        public Liegenschaft Liegenschaft { get; set; }
        public ICollection<Mietzins> MietzinsMenge { get; set; }
        public Objekt Objekt { get; set; }
    }
    
    public class Objekt
    {
        public int Id { get; set; }
        public int LiegenschaftId { get; set; }
        public int HausId { get; set; }
        public int Zimmer { get; set; }
    
        public Haus Haus { get; set; }
        public Liegenschaft Liegenschaft { get; set; }
        public ICollection<Mietzins> MietzinsMenge { get; set; }
        public ICollection<Mieter> MieterMenge { get; set; }
    }
    
    public class Liegenschaft
    {
        public int Id { get; set; }
        public string Strasse { get; set; }
        public int UserId { get; set; }
    
        public ICollection<Haus> HausMenge { get; set; }
        public ICollection<Mieter> MieterMenge { get; set; }
        public ICollection<Mietzins> MietzinsMenge { get; set; }
        public ICollection<Objekt> ObjektMenge { get; set; }
    }
    
    public class Haus
    {
        public int Id { get; set; }
        public int LiegenschaftId { get; set; }
        public int Nummer { get; set; }
    
        public ICollection<Objekt> ObjektMenge { get; set; }
        public Liegenschaft Liegenschaft { get; set; }
    }
    

    Context:

    public class ImmoReportsEntities : DbContext
    {
        public DbSet<Liegenschaft> Liegenschaft { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Liegenschaft>()
                .HasMany(e => e.HausMenge)
                .WithRequired(e => e.Liegenschaft)
                .HasForeignKey(e => e.LiegenschaftId)
                .WillCascadeOnDelete(false);
    
            modelBuilder.Entity<Liegenschaft>()
                .HasMany(e => e.MieterMenge)
                .WithRequired(e => e.Liegenschaft)
                .HasForeignKey(e => e.LiegenschaftId)
                .WillCascadeOnDelete(false);
    
            modelBuilder.Entity<Liegenschaft>()
                .HasMany(e => e.MietzinsMenge)
                .WithRequired(e => e.Liegenschaft)
                .HasForeignKey(e => e.LiegenschaftId)
                .WillCascadeOnDelete(false);
    
            modelBuilder.Entity<Liegenschaft>()
                .HasMany(e => e.ObjektMenge)
                .WithRequired(e => e.Liegenschaft)
                .HasForeignKey(e => e.LiegenschaftId)
                .WillCascadeOnDelete(false);
    
            modelBuilder.Entity<Haus>()
                .HasMany(e => e.ObjektMenge)
                .WithRequired(e => e.Haus)
                .HasForeignKey(e => e.HausId)
                .WillCascadeOnDelete(false);
    
            modelBuilder.Entity<Objekt>()
                .HasMany(e => e.MietzinsMenge)
                .WithRequired(e => e.Objekt)
                .HasForeignKey(e => e.ObjektId)
                .WillCascadeOnDelete(false);
    
            modelBuilder.Entity<Objekt>()
                .HasMany(e => e.MieterMenge)
                .WithRequired(e => e.Objekt)
                .HasForeignKey(e => e.ObjektId)
                .WillCascadeOnDelete(false);
    
            modelBuilder.Entity<Mieter>()
                .HasMany(e => e.MietzinsMenge)
                .WithRequired(e => e.Mieter)
                .HasForeignKey(e => e.MieterId)
                .WillCascadeOnDelete(false);
        }
    }
    

    I then ran your code exactly as in the question and it worked fine.

    I then changed the primary key of Mietzins so that it is no longer database generated:

    public class Mietzins
    {
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int Id { get; set; }
        public int LiegenschaftId { get; set; }
        public int MieterId { get; set; }
        public int ObjektId { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
    
        public Liegenschaft Liegenschaft { get; set; }
        public Mieter Mieter { get; set; }
        public Objekt Objekt { get; set; }
    }
    

    I ran the code again and got the following exception:

    Unhandled Exception: System.Data.Entity.Infrastructure.DbUpdateException:
    An error occurred while updating the entries.
    See the inner exception for details.
    —>
    System.Data.UpdateException: An error occurred while updating the entries.
    See the inner exception for details.
    —>
    System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint ‘PK_Mietzins’. Cannot insert duplicate key in object ‘dbo.Mietzins’.
    The statement has been terminated.

    If this is different than the exception you are seeing then please post your code and the full exception message and stack trace and I’ll take another look.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have just tried to save a simple *.rtf file with some websites and
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have some data like this: 1 2 3 4 5 9 2 6
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
I have a jquery bug and I've been looking for hours now, I can't
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text
this is what i have right now Drawing an RSS feed into the php,
I want use html5's new tag to play a wav file (currently only supported

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.