dotnet / efcore

EF Core is a modern object-database mapper for .NET. It supports LINQ queries, change tracking, updates, and schema migrations.
https://docs.microsoft.com/ef/
MIT License
13.79k stars 3.19k forks source link

Foreign Key string constraint failed #17905

Closed dandandandaann closed 2 years ago

dandandandaann commented 5 years ago

I have an issue like this: https://github.com/aspnet/EntityFrameworkCore/issues/16875 Except that my Key is String which is supposed to be already nullable.

I have these classes:

public class Transaction : Entity
{
    public string TransactionNumber { get; set; }
    public virtual ICollection<Movement> movements { get; set; }
}
public class Movement : Entity
{
    public int MovementId { get; set; }
    public string TransactionNumber { get; set; }
    public virtual Transaction Transaction { get; set; }
}

The configuration is setting the key:

builder.ToTable("Transaction");
builder.HasKey(d => d.TransactionNumber);

If I only create a new Movement with a TransactionNumber and save it I get a SqliteException: SQLite Error 19: 'FOREIGN KEY constraint failed'.. If a create both Movement and Transaction together it doesn't happen.
I tried changing the TransactionNumber to int? and it seems to work fine this way.

This issue is only happening in my test environment with Sqlite in memory creating the database codefirst. It's working fine in my production setup using MySql where the database is created independently.

Further technical details

EF Core version: Microsoft.EntityFrameworkCore 2.2.6 Database provider: Microsoft.EntityFrameworkCore.Sqlite 2.2.6 Target framework: NET Core 2.2

AndriySvyryd commented 5 years ago

@danielfdutra Please create a runnable project that shows this issue

dandandandaann commented 5 years ago

https://github.com/danielfdutra/EFCoreFKExceptionPoC

smitpatel commented 5 years ago

@danielfdutra - It throws exception because Transaction with TransactionNumber = C does not exist. A nullable FK property allows you to add Movement which does not belong to any Transaction but FK constraint will still block you to add Movement which references to a Transaction which does not exist.

smitpatel commented 5 years ago

@bricelam - I could not find the issue for unconstrainted relationships.

AndriySvyryd commented 5 years ago

https://github.com/aspnet/EntityFrameworkCore/issues/13146