The help for HasRequired
states
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. If I change to
HasOptional(b => b.Customer)
.WithOptionalPrincipal();
It fails with (Already at get from database)
Invalid column name '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.
HasOptional(c => c.Customer)
.WithOptionalPrincipal()
.Map(m => m.MapKey("BookingKey"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.