使外键(字符串字段)可为空
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
是可为空的外键,但它不是在 table
上那样创建的
CONSTRAINT [FK_dbo.Appointment_dbo.IdentityUser_ApplicationUserId] FOREIGN KEY ([ApplicationUserId]) REFERENCES [dbo].[IdentityUser] ([Id]),
谁能指出实现此目标的正确方法?
Note: I am using Entity framework code first approach
根据您的模型,我猜您正在尝试在 ApplicationUser
和 Appointment
之间创建一对多关系(一个用户可以拥有多个 Appointment
)。如果是这种情况,您可以通过以下方式在上下文的 OnModelCreating
方法中配置该关系:
modelbuilder.Entity<Appoiment>().HasOptional(a=>a.ApplicationUser)
.WithMany(au=>au.Appointments)
.HasForeignKey(a=>ApplicationUserId);
检查此 link 并转到“一对多关系的可为空的外键。”部分
对于 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);
}
我的模型是这样的
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
是可为空的外键,但它不是在 table
CONSTRAINT [FK_dbo.Appointment_dbo.IdentityUser_ApplicationUserId] FOREIGN KEY ([ApplicationUserId]) REFERENCES [dbo].[IdentityUser] ([Id]),
谁能指出实现此目标的正确方法?
Note: I am using Entity framework code first approach
根据您的模型,我猜您正在尝试在 ApplicationUser
和 Appointment
之间创建一对多关系(一个用户可以拥有多个 Appointment
)。如果是这种情况,您可以通过以下方式在上下文的 OnModelCreating
方法中配置该关系:
modelbuilder.Entity<Appoiment>().HasOptional(a=>a.ApplicationUser)
.WithMany(au=>au.Appointments)
.HasForeignKey(a=>ApplicationUserId);
检查此 link 并转到“一对多关系的可为空的外键。”部分
对于 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);
}