簡體   English   中英

使外鍵(字符串字段)可為空

[英]Make Foreign Key (string field) nullable

我的模特是這樣的

 public class Appointment
{
    public int AppointmentID { get; set; }
    public string AppointmentCode { get; set; }
    public string ApplicationUserId { get; set; }
    [ForeignKey("ApplicationUserId ")]
    public ApplicationUser ApplicationUser { get; set; }
    public int PriceId { get; set; }
}

我希望ApplicationUserId可以為可空的外鍵,但它不是像桌面上那樣創建的

  CONSTRAINT [FK_dbo.Appointment_dbo.IdentityUser_ApplicationUserId] FOREIGN KEY ([ApplicationUserId]) REFERENCES [dbo].[IdentityUser] ([Id]),

有人能指出正確的方法來實現這一目標嗎?

注意:我使用Entity框架代碼的第一種方法

根據您的模型,我猜您正在嘗試在ApplicationUserAppointment之間創建一對多關系(一個用戶可以有多個Appointment )。 如果是這種情況,您可以通過OnModelCreating方式在上下文中的OnModelCreating方法中配置該關系:

modelbuilder.Entity<Appoiment>().HasOptional(a=>a.ApplicationUser)
                                .WithMany(au=>au.Appointments)
                                .HasForeignKey(a=>ApplicationUserId);

檢查此鏈接並轉到“ 可以為一對多關系的可空外鍵 ”部分

對於EF核心,您可以在OnModelCreating中編寫以下代碼:

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<Appoiment>().HasOne(a => a.ApplicationUser)
                .WithMany(au => au.Appointments)
                .HasForeignKey(a => a.ApplicationUserId)
                .IsRequired(false);

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM