0

In Using EF6 in C# :- i have Model A which has Model B and C inside it.

class A
{
    Guid Id;
    B b;
    C c;

    public A()
    {
        Id = new Guid;
    }
}

class B
{
    Guid Id;

    public B()
    {
        Id = new Guid;
    }
}

When model A saved in database (without B and C) its working fine. When i fetch it from database and then create new B and assign it to A and try to save it. Getting error

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.

An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.

(I have all the keys as GUID). On further debug i can see EntityKey is null for B in Exception. enter image description here

I have tired this link1,link2 but non of this solution are working.

Varun Jain
  • 495
  • 3
  • 9
  • 22

1 Answers1

0

First of all I would use properties instead of fields.

Then as I see you have a one-to-one relationship between A and B and also between A and C where B and C are optional.

"When configuring one-to-one relationships, Entity Framework requires that the primary key of the dependent also be the foreign key." - Programming Entity Framework Code First by Julia Lerman & Rowan Miller

So the other problem is that in class B you set the value of Id through the constructor.

I would try this below:

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace EFExposeForeignKey
{
    public class A
    {
        public A()
        {
            Id = Guid.NewGuid();
        }

        [Key]
        public Guid Id { get; set; }

        /* Other properties of A goes here */

        // Navigation property
        public B B { get; set; }

        // Navigation property
        public C C { get; set; }
    }

    public class B
    {
        [Key]
        [ForeignKey(nameof(EFExposeForeignKey.A.B))]
        // Or simply [ForeignKey("B")]
        // I wanted to emphasize here that "B" is NOT the type name but the name of a property in class "A"
        public Guid Id { get; set; }

        /* Other properties of B goes here */

        // Navigation property
        public A A { get; set; }
    }

    public class C
    {
        [Key]
        [ForeignKey(nameof(EFExposeForeignKey.A.C))]
        public Guid Id { get; set; }

        /* Other properties of C goes here */

        // Navigation property
        public A A { get; set; }
    }
}
Gabor
  • 3,021
  • 1
  • 11
  • 20