简体   繁体   English

C# 实体框架代码优先 - 如何仅使用该外键的 id 添加带有外键的行?

[英]C# Entity Framework Code-First- How do you add a row with foreign key using just the id of that foreign key?

If I have the following classes (using CodeFirst Entity Framework):如果我有以下类(使用 CodeFirst Entity Framework):

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; }
}

When adding a new notification, whats the most efficient way to say notification.status = 1 ?添加新通知时,说notification.status = 1的最有效方式是什么? Do I have to query the DB each time to get the list available?我是否必须每次都查询数据库才能获得可用的列表?

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

I feel like hitting the DB this many times is inefficient but I do want these values normalized and in the db.我觉得多次访问数据库效率低下,但我确实希望这些值标准化并在数据库中。

Any suggestions or is the way I'm doing NotificationType & Frequency the only way?有什么建议或者我做NotificationType & Frequency的方式是唯一的方法吗?

Thanks!谢谢!

You have to fix your class.您必须修复您的 class。 Add Id fields:添加 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; }
}

in this case:在这种情况下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM