gpt4 book ai didi

c# - 外键长时多对一迁移失败

转载 作者:太空宇宙 更新时间:2023-11-03 18:58:06 25 4
gpt4 key购买 nike

我有两个模型:

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 { get; set; }
}

我建立在用户之上的模型是

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

当我尝试运行时:

dotnet ef migrations add

我收到这个错误:

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.

更新:

新模型应该能够拥有表格文本的集合,例如:

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

最佳答案

使用 EF Core 时遇到了类似的问题,但不想在依赖实体文本上包含(在我的类中等效的)UserId,只是为了让 EF 开心。终于发现可以替换关系中使用的主键(UserId)使用 HasPrincipalKey()

    modelBuilder.Entity<User>()
.HasMany(t => t.Texts)
.WithOne()
.HasPrincipalKey(u => u.Text);

关于c# - 外键长时多对一迁移失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40844081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com