简体   繁体   English

HasRequired的奇怪行为

[英]Strange behavior with HasRequired

The help for HasRequired states HasRequired状态的帮助

Configures a required relationship from this entity type. 从此实体类型配置所需的关系。 Instances of the entity type will not be able to be saved to the database unless this relationship is specified. 除非指定了这种关系,否则实体类型的实例将无法保存到数据库。 The foreign key in the database will be non-nullable. 数据库中的外键将不可为空。

I have a none required field configured like 我有一个不需要的字段配置为

public class BookingConfiguration : EntityTypeConfiguration<Booking>
    {
        public BookingConfiguration()
        {
            HasKey(ai => ai.BookingKey);

            ...

            HasRequired(b => b.Customer)
                .WithRequiredPrincipal();

            ToTable("Booking");
        }
    }

This is ofcourse very strange since Customer is not required. 当然这是很奇怪的,因为不需要客户。 But, it works :D Both for null values and when customer is set. 但是,它:D都适用于空值和设置客户时。 If I change to 如果我更改为

HasOptional(b => b.Customer)
    .WithOptionalPrincipal();

It fails with (Already at get from database) 它失败并(已从数据库获取)

Invalid column name 'Booking_BookingKey'. 无效的列名“ Booking_BookingKey”。

The code that fails 失败的代码

var existingBooking = await _context.DbSet<Booking>().FirstAsync(ai => ai.BookingKey == confirmCommand.BookingKey);

edit: Structure of entities are 编辑:实体的结构是

public class Booking
{
   public Guid BookingKey { get; set; }
   ...
   public Customer Customer { get; set; }
}

public class Customer
{
   public Guid BookingKey { get; set; }
   ...   
}

Since BookingKey is both the Key for Booking and the ForeignKey for Customer try setting the ForeignKey field during setup. 由于BookingKey既是预订的密钥,也是客户的ForeignKey,因此请尝试在设置过程中设置ForeignKey字段。

HasOptional(c => c.Customer)
     .WithOptionalPrincipal()
     .Map(m => m.MapKey("BookingKey"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM