在EF Core中保存嵌套的objescs会抛出InvalidOperationException

时间:2016-07-22 14:07:06

标签: c# entity-framework-core

考虑到我从服务中获得了以下JSON,将其插入到EF Core托管的sqlite数据库中的最佳方法是什么?

关系将是:

付款方式付款 - >许多对一

支付类型到PayentUnit - >许多对一

我不需要退回给父母,如支付类型POCO中的付款清单,还是我?

{
    "payments": [{
        "id": 1,
        "paymentType": {
            "id": 1,
            "paymentUnit": {
                "id": 1
            }
        }
    }, {
        "id": 2,
        "paymentType": {
            "id": 2,
            "paymentUnit": {
                "id": 2
            }
        }
    }, {
        "id": 3,
        "paymentType": {
            "id": 2,
            "paymentUnit": {
                "id": 2
            }
        }
    }, {
        "id": 4,
        "paymentType": {
            "id": 4,
            "paymentUnit": {
                "id": 1
            }
        }
    }]
}

public class Response
{
    public List<Payment> Payments { get; set; }
}

public class Payment
{
    public int Id { get; set; }
    public PaymentType PaymentType { get; set; }
}

public class PaymentType
{
    public int Id { get; set; }
    public PaymentUnit PaymentUnit { get; set; }
}

public class PaymentUnit
{
    public int Id { get; set; }
}

在我的OnModelCreating上,我已经映射了键: 我将Id标记为OnModelCreating:

上的键
modelBuilder.Entity<Payment>()
    .Property(p => p.Id)
    .ValueGeneratedNever();

modelBuilder.Entity<Payment>()
    .HasKey(p => p.Id);

modelBuilder.Entity<PaymentType>()
    .Property(pt => pt.Id)
    .ValueGeneratedNever();

modelBuilder.Entity<PaymentType>()
    .HasKey(pt => pt.Id);

modelBuilder.Entity<PaymentUnit>()
    .Property(pu => pu.Id)
    .ValueGeneratedNever();

modelBuilder.Entity<PaymentUnit>()
    .HasKey(pu => pu.Id);

但是当我尝试做一个context.Payment.AddRamge(付款)时,我得到一个像https://github.com/aspnet/EntityFramework/issues/3839这样的例外。一切都在干净的DB上。我已经创建了迁移和所有。

提前感谢!

0 个答案:

没有答案
相关问题