c# - 使用 entityFramework 插入包含 IEnumerable 属性的模型

标签 c# entity-framework

我有以下两个模型:

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 列表的类在这里(它们是大型类文件) https://gist.github.com/anonymous/67a2ae0192257ac51f39

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

EF 是否可以实现此功能?

最佳答案

尝试将您的 IEnumerable 更改为实现 ICollection 的东西,例如 List
参见 this回答更多详情

关于c# - 使用 entityFramework 插入包含 IEnumerable 属性的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30219634/

相关文章:

c# - 如何选择最后一小时和groupby分钟?

c# - Entity Framework 和三层架构

c# - LINQ to Entities 中的多对多选择

c# - 选择中的 Entity Framework 条件

c# - 无法通过c#代码将小数插入到sql server表中

c# - MD5 哈希在 C# 和 Objective C 中不相似

c# - XmlEnumAttribute 在 WCF 请求中不起作用

c# - 如何将 F4 键发送到 C# 中的进程?

C# 测试 null

linq - 按日期过滤查询