C# 使外键(字符串字段)为空
我的模型是这样的C# 使外键(字符串字段)为空,c#,asp.net-mvc,entity-framework,ef-code-first,C#,Asp.net Mvc,Entity Framework,Ef Code First,我的模型是这样的 public class Appointment { public int AppointmentID { get; set; } public string AppointmentCode { get; set; } public string ApplicationUserId { get; set; } [ForeignKey("ApplicationUserId ")] public ApplicationUser Applic
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; }
}
我希望applicationserid
是可为空的外键,但它不是像表中那样创建的
CONSTRAINT [FK_dbo.Appointment_dbo.IdentityUser_ApplicationUserId] FOREIGN KEY ([ApplicationUserId]) REFERENCES [dbo].[IdentityUser] ([Id]),
有人能指出实现这一目标的正确方法吗
注意:我使用的是实体框架代码优先的方法
根据您的模型,我猜您正在尝试在
应用程序用户
和约会
之间创建一对多关系(一个用户可以有多个约会
)。如果是这种情况,您可以通过以下方式在上下文的OnModelCreating
方法中配置该关系:
modelbuilder.Entity<Appoiment>().HasOptional(a=>a.ApplicationUser)
.WithMany(au=>au.Appointments)
.HasForeignKey(a=>ApplicationUserId);
modelbuilder.Entity并转到“一对多关系的可空外键”部分。对于EF core,您可以在OnModelCreating中编写以下代码:
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Appoiment>().HasOne(a => a.ApplicationUser)
.WithMany(au => au.Appointments)
.HasForeignKey(a => a.ApplicationUserId)
.IsRequired(false);
}
模型创建时受保护的覆盖无效(ModelBuilder)
{
builder.Entity().HasOne(a=>a.ApplicationUser)
.有许多(au=>au.预约)
.HasForeignKey(a=>a.ApplicationSerID)
.i被要求(虚假);
}
也许这会回答您的问题,这是什么版本的EF?顺便说一句,您可以使用DbMigration类中的Up方法为架构生成内容设置自己的逻辑。这会引发编译时错误1类型“string”必须是不可为null的值类型,才能在泛型类型或方法“System.nullable”App\Models\Appointment.cs 104 24 diagnosis中用作参数“T”。这是真的,字符串是引用类型,所以您不需要将该属性声明为可为null,只需使用配置即可。