【问题标题】:Model Containing a IEnumerable property insert using entityFramework包含使用 entityFramework 插入的 IEnumerable 属性的模型
【发布时间】:2015-07-25 00:35:41
【问题描述】:

我有以下两种型号:

public class Alert
{
    public int Id { get; set; }
    public DateTime AlertDatetime { get; set; }
    public bool Unread { get; set; }
    public int? ReadByUserId { get; set; }
    public DateTime? ReadDateTime { get; set; }
    public DateTime ImportDateTime { get; set; }
    public bool AlertHasRecords { get; set; }

    //Error Reporting and Recording.
    public bool Error { get; set; }
    public string ErrorText { get; set; }

    public virtual IEnumerable<AlertRecord> Records { get; set; }
}


public class AlertRecord
{
    public int Id { get; set; }
    public string HospitalNumber { get; set; }
    public string ForeName { get; set; }
    public string SurName { get; set; }
    public DateTime DateOfBirth { get; set; }
    public DateTime EventDateTime { get; set; }
    public string CrisNumber { get; set; }

    public DateTime CreationDateTime { get; set; }

    //Link it back to the master Alert!
    public int AlertId { get; set; }
    public virtual Alert Alert { get; set; }
}

一旦“警报”对象属性中有值,我将尝试使用 EntityFramework 将此对象插入到我的 SQL 数据库中,如下所示:

class Program
{
    private static Alert MainAlert = new Alert();
    private static PrimaryDBContext db = new PrimaryDBContext();

    static void Main(string[] args)
    {
        MainAlert = AlertObjectFactory.GetAlertObject();            
        db.Alerts.Add(MainAlert);
        db.SaveChanges();
    }
}

AlertObjectFactory.cs 和负责构建 AlertRecords 列表的 Class 在这里(它们是大型类文件) https://gist.github.com/anonymous/67a2ae0192257ac51f39

“警报”表正在填充数据,但 4 条记录在 IEnumerable 记录 没有被插入...

EF 是否可以实现此功能?

【问题讨论】:

  • 我看不到您将 4 AlertRecords 添加到您的 MainAlert 的位置。
  • 我们需要在GetAlertObject() 方法中查看您的代码。我们仍然看不到您在哪里填充数据。
  • @DStanley 我已经编辑了我的问题,以显示对我的“AlertObjectFactory”的方法调用,该类负责用其数据填充对象。
  • 我已将 2 个有问题的类文件上传到 Gist,因为它们非常大。在 Records 属性中生成数据的类是:AlertRecordImporter.GetAlertObjects()

标签: c# entity-framework


【解决方案1】:

尝试将您的 IEnumerable 更改为实现 ICollection 的内容,例如 List
更多详情见this答案

【讨论】:

  • 完美,解决了问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多