使外键(字符串字段)可为空

时间:2015-04-08 09:40:33

标签: 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; }
}

我希望ApplicationUserId是可以为空的外键,但它不是像桌子上那样创建的

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

有人能指出正确的方法来实现这个目标吗?

  

注意:我正在使用Entity框架代码第一种方法

2 个答案:

答案 0 :(得分:5)

根据您的模型,我猜您尝试在ApplicationUserAppointment之间创建一对多关系(一个用户可以拥有多个Appointment)。如果是这种情况,您可以通过以下方式在上下文的OnModelCreating方法中配置该关系:

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

选中此link并转到&#34; Nullable外键以获得一对多关系。&#34;

答案 1 :(得分:1)

对于EF核心,您可以在OnModelCreating:

中编写以下代码
fwrite("&tm->tm_mon+1", sizeof(tm->tm_mon+1),1,fptr);
fwrite("&tm->tm_mday", sizeof(tm->tm_mday+1),1,fptr);
fwrite("&tm->tm_hour", sizeof(tm->tm_hour+1),1,fptr);
fwrite("&tm->tm_sec", sizeof(tm->tm_sec+1),1,fptr);
fwrite("&frame_rd->can_id", sizeof(frame_rd->can_id),1,fptr);
fwrite("&frame_rd->data", sizeof(frame_rd->data),1,fptr);
相关问题