An error occurred while saving entities that do not expose foreign key properties for their relationships

C#Entity FrameworkEf Code-FirstEntity Framework-4.1

C# Problem Overview


I have a simply code in Entity Framework 4.1 code first:

PasmISOContext db = new PasmISOContext();
var user = new User();
user.CreationDate = DateTime.Now;
user.LastActivityDate = DateTime.Now;
user.LastLoginDate = DateTime.Now;
db.Users.Add(user);

db.SaveChanges();
user.Avatar = new Avatar() { Link = new Uri("http://myUrl/%2E%2E/%2E%2E") };
db.SaveChanges();


db.Users.Add(new User() { Avatar = new Avatar() { Link = new Uri("http://myUrl/%2E%2E/%2E%2E") } });
db.SaveChanges();

The problem is that I get an error

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

at

db.Users.Add(new User() { Avatar = new Avatar() { Link = new Uri("http://myUrl/%2E%2E/%2E%2E") } });
db.SaveChanges();
  

I don't understand why the similar operation works. Is there something wrong with my model, or with ef-code-first?

public class Avatar
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string LinkInString { get; set; }

    [NotMapped]
    public Uri Link
    {
        get { return new Uri(LinkInString); }
        set { LinkInString = value.AbsoluteUri; }
    }
}

public class User
{
    [Key]
    public int Id { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public Avatar Avatar { get; set; }
    public virtual ICollection<Question> Questions { get; set; }
    public virtual ICollection<Achievement> Achievements { get; set; }

    public DateTime CreationDate { get; set; }
    public DateTime LastLoginDate { get; set; }
    public DateTime LastActivityDate { get; set; }
}

C# Solutions


Solution 1 - C#

For those of you who would still have this error with all keys properly defined, have a look at your entities and make sure you don't leave a datetime field with a null value.

Solution 2 - C#

This error message can be thrown for any kind of reason. The 'InnerException' property (or its InnerException, or the InnerException of that, etc) contains the actual primary cause of the problem.

It would of course be useful to know something about where the problem occurred - which object(s) in the unit of work is causing the problem? The exception message would normally tell you in the 'EntityEntries' property, but in this case, for some reason, that can't be done. This diagnostic complication - of the 'EntityEntries' property being empty - is apparently because some Entities 'do not expose foreign key properties for their relationships.'

Even if the OP gets the error because of failing to initialize DateTimes for the second instance of User, they get the diagnostic complication - 'EntityEntries' being empty, and a confusing top-level message ... because one of their Entity's doesn't 'expose foreign key properties'. To fix this, Avatar should have a public virtual ICollection<User> Users { get; set; } property defined.

Solution 3 - C#

The issue was resolved by adding an FK property.

Solution 4 - C#

In my case the following situation was giving me the same Exception:

Imagine a code first EF model where you have a Garage entity that has a collection of Car entities. I needed to remove a car from the garage so I ended up with code that looked like this:

garageEntity.Cars.Remove(carEntity);

Instead, it should've been looked like this:

context.Cars.Remove(carEntity);

Solution 5 - C#

Just for others who might have similar problems. I had the same error, but for a different reason. In one of the child objects I defined the [Key] as being a value which was the same for different saves. A stupid mistake on my part, but the error message does not instantly lead you to the problem.

Solution 6 - C#

In my case the exeception was thrown because EF had created a migration incorrectly. It missed setting the identity: true on the second table. So go into the migrations which created the relevant tables and check if it missed to add identity.

CreateTable(
    "dbo.LogEmailAddressStats",
    c => new
        {
            Id = c.Int(nullable: false, identity: true),
            EmailAddress = c.String(),
        })
    .PrimaryKey(t => t.Id);
      
CreateTable(
    "dbo.LogEmailAddressStatsFails",
    c => new
        {
            Id = c.Int(nullable: false), // EF missed to set identity: true!!
            Timestamp = c.DateTime(nullable: false),
        })
    .PrimaryKey(t => t.Id)
    .ForeignKey("dbo.LogEmailAddressStats", t => t.Id)
    .Index(t => t.Id);

An Id column should have identity (i.e. auto-incrementing!) so this must be a EF bug.

You could add identity manually with SQL directly to the database but I prefer using Entity Framework.

If you run in to the same problem I see two easy solutions:

Alt 1

reverse the incorrectly created migration with

update-database -target:{insert the name of the previous migration}

Then add the identity: true manually to the migration code and then update-database again.

Alt 2

you create a new migration that adds identity. If you have no changes in the models and you run

add-migration identity_fix

it will create an empty migration. Then just add this

    public partial class identity_fix : DbMigration
    {
        public override void Up()
        {
            AlterColumn("dbo.LogEmailAddressStatsFails", "Id", c => c.Int(nullable: false, identity: true));
        }
        
        public override void Down()
        {
            AlterColumn("dbo.LogEmailAddressStatsFails", "Id", c => c.Int(nullable: false));
        }
    }

Solution 7 - C#

This problem can also arise from reversed key declarations. If you're using fluent to configure the relationship, make sure the left and right keys are mapped to the correct entity.

Solution 8 - C#

I hade same probleme. in my case, it was due to datetime field with a null value. I had to passe a value to datetime and evrythings went fine

Solution 9 - C#

Another answer:

I used this:

public List<EdiSegment> EdiSegments { get; set; }

instead of this:

public virtual ICollection<EdiSegment> EdiSegments { get; set; }

and got the error message noted above.

Solution 10 - C#

I had the same error and in my case the problem was that I added a relationship object which had already been loaded "AsNoTracking". I had to reload the relation property.

BTW, Some suggest using "Attach" for relations that already exist in db, I haven't tried that option though.

Solution 11 - C#

In my case, the problem was that I renamed a column improperly, so the migration made two columns, one called "TeamId" and one called "TeamID". C# cares, SQL doesn't.

Solution 12 - C#

Yet another different case here. A query was cast to a list and while doing that, it created entities by their constructor for comparison in the linq expression right after the ToList(). This created entities that gotten into the deleted state after the linq expression finished.
However! There was a small adjustment that created another entity in the constructor, so that this new entity got linked to an entity that was marked as Deleted.

Some code to illustrate:

query.Except(_context.MyEntitySetSet()
                .Include(b => b.SomeEntity)
                .Where(p => Condition)
                .ToList() // This right here calls the constructor for the remaining entities after the where
                .Where(p => p.Collection.First(b => Condition).Value == 0)
                .ToList();

The constructor of MyEntity:

public partial class MyEntity
{
    protected MyEntity()
    {
        // This makes the entities connected though, this instance of MyEntity will be deleted afterwards, the instance of MyEntityResult will not.
        MyEntityResult = new MyEntityResult(this);
    }
}

My solution was to make sure the entire expression was done inside the IQueryable so that there won't be any objects created.

Solution 13 - C#

I'm not entirely sure that it's going to help in your case because I'm setting up my tables using Fluent API, however, as far I can tell, the issue arises regardless whether the schema is set up using data annotations (attributes) or Fluent API (configuration).

There seems to be a bug in EF (v. 6.1.3) as it omits certain changes to the schema when updating the DB to the next migration. The quickest route around it is (during the development stage) to remove all the tables from the DB and runt migrations from init stage again.

If you're already in production, the quickest solution I've found was to manually change the schema in the DB or, if you want to have version control of the changes, manually manipulate the methods Up() and Down() in your migration.

Solution 14 - C#

Today I faced this issue and tried the possible solutions posted above but none of them helped me. I had UnitOfWork pattern implemented and system was committing the data in last after adding all the records.

In my case system was combining the two models and querying the DB

> Invalid object name 'dbo.RoleModelUserModel'.

where these were two different models actually.

I fixed this by reordering the insert statements and adding the parent entity first. In this case added the user first and issue resolved.

Solution 15 - C#

After a bit of investigation I found that whilst .Net supports a minimum date (DateTime.MinValue) of 01/01/0001 00:00:00 and a maximum (DateTime.MaxValue) of 31/12/9999 23:59:59 in SQL Server Compact Edition minimum date is 01/01/1753 00:00:00. When I entered a date greater than 01/01/1753 00:00:00, this error disappeared.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser278618View Question on Stackoverflow
Solution 1 - C#BaralView Answer on Stackoverflow
Solution 2 - C#David BullockView Answer on Stackoverflow
Solution 3 - C#user278618View Answer on Stackoverflow
Solution 4 - C#Memet OlsenView Answer on Stackoverflow
Solution 5 - C#Simon The CatView Answer on Stackoverflow
Solution 6 - C#fredrik.hjarnerView Answer on Stackoverflow
Solution 7 - C#EdynView Answer on Stackoverflow
Solution 8 - C#onlymeView Answer on Stackoverflow
Solution 9 - C#Greg GumView Answer on Stackoverflow
Solution 10 - C#HamedView Answer on Stackoverflow
Solution 11 - C#DustonView Answer on Stackoverflow
Solution 12 - C#MixxiphoidView Answer on Stackoverflow
Solution 13 - C#Konrad VilterstenView Answer on Stackoverflow
Solution 14 - C#Nawaz KhanView Answer on Stackoverflow
Solution 15 - C#Andrei KrasutskiView Answer on Stackoverflow