user3387996 user3387996 - 4 days ago 6
C# Question

Many to one migrations fails on foreign key long

I have 2 models

public class Text
{
public long Id { get; set; }
public string Text{ get; set; }
}


public class User
{
public int Id { get; set; }
public ICollection<Text>Texts
}


My model build on user is that

e.HasMany(o => o.Texts).WithOne().HasForeignKey(d => d.Id).IsRequired();


when i try to run :


dotnet ef migrations add


I get -->


with foreign key properties {'Id' : long} cannot target the primary
key {'Id' : int} because it is not compatible. Configure a principal
key or a set of compatible foreign key properties for this
relationship.


UPDATE :

It should be able for new models to have a collection of the table Texts like :

public class Customer
{
public int Id { get; set; }
public ICollection<Text>Texts { get; set; }
}


....
e.HasMany(o => o.Texts).WithOne().HasForeignKey(d => d.Id).IsRequired();

Answer

In the EF context configuration, specifically in the HasForeignKey() you are supposed to specify Which property on the Text model should be the foreign key that points to the User model?

Since User model's primary key is an int, the foreign key pointing from Text to User should naturally also be an int.

I think the mistake you've made is that you are configuring the PK of Textto also be the FK for the relationship Text -> User. Try to change your Text model to :

public class Text
{
   public long Id { get; set; }
   public string Text{ get; set; }
   public int UserId { get; set; }
}

And your configuration to:

e.HasMany(o => o.Texts).WithOne().HasForeignKey(d => d.UserId).IsRequired();
Comments