简体   繁体   中英

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):

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 ? 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?

Thanks!

You have to fix your class. Add Id fields:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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