Ath*_*hul 4 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 ApplicationUser { get; set; }
public int PriceId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我期待ApplicationUserId可以为空的外键,但它不是像桌面上那样创建的
CONSTRAINT [FK_dbo.Appointment_dbo.IdentityUser_ApplicationUserId] FOREIGN KEY ([ApplicationUserId]) REFERENCES [dbo].[IdentityUser] ([Id]),
Run Code Online (Sandbox Code Playgroud)
有人能指出正确的方法来实现这一目标吗?
注意:我使用Entity框架代码的第一种方法
根据你的模型,我猜你正在尝试在ApplicationUser和之间建立一对多的关系Appointment(一个用户可以拥有多个Appointment).如果是这种情况,您可以通过以下OnModelCreating方式在上下文中的方法中配置该关系:
modelbuilder.Entity<Appoiment>().HasOptional(a=>a.ApplicationUser)
.WithMany(au=>au.Appointments)
.HasForeignKey(a=>ApplicationUserId);
Run Code Online (Sandbox Code Playgroud)
检查这个链接,进入到部分" 空的外键一到多的关系. "
对于 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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3966 次 |
| 最近记录: |