我的模型是这样的
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
可以为 nullable Foreign Key ,但它不是像表上那样创建的
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
之间创建一对多关系(一个用户可以拥有多个 约会
).如果是这种情况,您可以通过以下方式在上下文的 OnModelCreating
方法中配置该关系:
modelbuilder.Entity<Appoiment>().HasOptional(a=>a.ApplicationUser)
.WithMany(au=>au.Appointments)
.HasForeignKey(a=>ApplicationUserId);
检查这个link并转到“一对多关系的可为空的外键。”部分
关于c# - 使外键(字符串字段)可为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29511083/