微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C# Entity Framework Code-First - 如何仅使用外键的 id 添加带有外键的行?

如何解决C# Entity Framework Code-First - 如何仅使用外键的 id 添加带有外键的行?

如果我有以下类(使用 CodeFirst 实体框架):

public class Notifications
{
    [Key]
    public int ID { get; set; }
    public virtual ClientDetails Client { get; set; }
    public virtual NotificationTypes NotificationType { get; set; }
    public virtual NotificationFreqs Frequency { get; set; }
    public virtual NotificationStatus Status { get; set; }
    public DateTime SendDate { get; set; }
    public DateTime? SentDate { get; set; }
    public DateTime QueueDate { get; set; }
}

public class NotificationFreqs
{
    [Key]
    public int ID { get; set; }
    [MaxLength(25)]
    public string Name { get; set; }
}

public class NotificationStatus
{
    [Key]
    public int ID { get; set; }
    [MaxLength(25)]
    public string Status { get; set; }
}

添加通知时,最有效的说 notification.status = 1 方式是什么? 我是否每次都必须查询数据库才能获得可用列表?

var notification = new Notifications();

var notificationType = db.NotificationTypes.FirstOrDefault(n => n.ID == notificationTypeId);
var notificationFreq = db.NotificationFreqs.FirstOrDefault(n => n.Name == setting.Value);

notification.NotificationType = notificationType; // Works
notification.Frequency = notificationFreq; // Works
notification.Status = new NotificationStatus { ID = 1 };  // ObvIoUsly doesn't work

我觉得多次访问数据库效率低下,但我确实希望这些值标准化并在数据库中。

有什么建议吗,或者我的做法是 NotificationTypeFrequency 的唯一方法

谢谢!

解决方法

你必须修复你的课程。添加 ID 字段:

public class Notifications
{
    [Key]
    public int ID { get; set; }
    public virtual ClientDetails Client { get; set; }

    [ForeignKey("NotificationType")]
    public int? Type_ID  { get; set; }
    public virtual NotificationTypes NotificationType { get; set; }

    [ForeignKey("Frequency")]
    public int? Frequency_ID { get; set; }
    public virtual NotificationFreqs Frequency { get; set; }

    [ForeignKey("Status")]
    public int? Status_ID { get; set; }
    public virtual NotificationStatus Status { get; set; }

    public DateTime SendDate { get; set; }
    public DateTime? SentDate { get; set; }
    public DateTime QueueDate { get; set; }
}

在这种情况下:

notification.Type_ID = notificationTypeId; 
notification.Frequency_ID = notificationFreq.ID; 
notification.Status_ID = 1

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。