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

entity framework foreign key mapping
c# foreign key entity framework
entity framework foreign key in model
primary key foreign key entity framework
the conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
add foreign key constraint entity framework
entity framework retrieve data from table with foreign key
entity framework navigation properties

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

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.

Resolve Entity Framework “An error occurred while saving entities , Resolve Entity Framework “An error occurred while saving entities that do not expose foreign key properties for their relationships” exception due to an empty string. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. 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.

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.

Foreign Key Properties, DbUpdateException was caught An error occurred while saving entities that do not expose foreign key properties for their relationships. 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.

The issue was resolved by adding an FK property.

https://social.msdn.microsoft.com/Forums/en-US/860, One of the main useful things EF does is make a relational database look This is very clever, but to do this EF's view of the database relationships must An error occurred while saving entities that do not expose foreign key can be made easier by exposing foreign key properties in your entity types. 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.

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

Handling Entity Framework database migrations in production – part , In the scenario I have a single Grupp referencing a single Objekt which links to error occurred while saving entities that do not expose foreign key can be made easier by exposing foreign key properties in your entity types. 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.'

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.

Many to Many relationship error when deleting · Issue #84 , 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. DbUpdateException: 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.

Error on saving a document - V5 Issue, Hi @emre I am experiencing a very weird issue with saving a new created document transaction. DbUpdateException Message: 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  Additional information: 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.

Error 500 deleting deployment step - Uncategorised, Error: 500 Server error: An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will 

DbUpdateException with entities that do not expose foreign key , EF is considering User as the dependent side of the relationship, and is I don't believe it's possible to use a foreign key property on either entity to help EF An error occurred while saving entities that do not expose foreign key properties for 

Comments
  • I cannot reproduce the error. Can you check the first code snippet? Is that excactly what your are doing? (At least one db.Users.Add(user) seems to be missing, otherwise the 2 SaveChanges make no sense.) Do you have any additional Fluent API mapping?
  • Thanks Slauma. I've edited my code. I haven'y any Fluent API. First and second SaveChanges add row to Avatars, and Users tables. I don't know if this is important, but in table I have Avatar_Id column.
  • Avatar_Id in User table is the foreign key column for the Avatar navigation property, that's OK. Did you create the database tables manually or did you let EF create the database? At the moment I have no idea why you get this error. You could try to follow the advice given in the exception and add a foreign key property to your User class: public int? AvatarId { get; set; } and see what happens. Perhaps at least the exception will reveal more details where the problem exactly is.
  • I let EF cretate the database. As you said I've added this property and now it works fine - now I have AvatarId instead Avatar_Id and it keeps correct avatarid. It weird , but thanks for helping me.
  • You could post it as an answer that the FK property fixed the problem and then accept your answer, just to finish this question. I don't understand why it solved your problem, for me it also worked without the FK property.
  • If you look at the inner exceptions, there is an exception of type "System.Data.SqlClient.SqlException" with message: "The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value." This results from having a null DateTime value being inserted into a column with null values not allowed. See stackoverflow.com/questions/1331779/….
  • My inner exception did not have anything related to datetime2 conversion, but I was setting a datetime to null. The DB column allows nulls, so I assumed that wasn't the problem, but it turned out it was. Try this even if you don't think it's your problem!
  • hello @SarangK can you tel how do you fix this problem
  • Thank you, it helped and saved me a lot of time !
  • @MohamedElgarnaoui I checked all DateTime fields to be initialized before 'context.SaveChanges();'
  • I stumbled upon this answer. I was receiving this fault during database initialization (dropcreatedb). I already had a foreign key, but making it nullable resolved my issue
  • Assuming a Car MUST have a Garage, yes. Because else you'd be trying to pass a null for GarageId in your Car object.
  • This one caught me out with a table rename. Thanks.