Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/264.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 实体框架向模型添加集合未正确保存_C#_Asp.net Mvc_Entity Framework_Ef Code First - Fatal编程技术网

C# 实体框架向模型添加集合未正确保存

C# 实体框架向模型添加集合未正确保存,c#,asp.net-mvc,entity-framework,ef-code-first,C#,Asp.net Mvc,Entity Framework,Ef Code First,也许是个简单的问题,但我似乎想不出来。将模型添加到数据库时将集合保存到模型不起作用。我有一个网站,它使用asp.NETMVC和实体框架 模型: public class Event { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public ICollection<EventRange> R

也许是个简单的问题,但我似乎想不出来。将模型添加到数据库时将集合保存到模型不起作用。我有一个网站,它使用asp.NETMVC和实体框架

模型:

public class Event
{
    public int Id { get; set; }

    public string Name { get; set; }
    public string Description { get; set; }

    public ICollection<EventRange> Ranges { get; set; }
}

public class EventRange
{
    public int Id { get; set; }

    public string RangeName { get; set; }
    public string RangeDescription { get; set; }

    public int Capacitiy { get; set; }
}
公共类事件
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共字符串说明{get;set;}
公共ICollection范围{get;set;}
}
公共类事件范围
{
公共int Id{get;set;}
公共字符串RangeName{get;set;}
公共字符串RangeDescription{get;set;}
公共int capacity{get;set;}
}
控制器操作:

[HttpPost]
public ActionResult Create(Event model)
{
    ICollection<EventRange> eventRanges = new Collection<EventRange>();
    var range = new EventRange {RangeName = "testrange", RangeDescription = "test", Capacitiy = 5}

    eventRanges.Add(range);
    model.Ranges = eventRanges;

    db.Events.Add(model);
    db.SaveChanges();

    return View();
}

public ActionResult Events()
{
    return View(db.Events);
}
[HttpPost]
公共操作结果创建(事件模型)
{
ICollection eventRanges=新集合();
var range=neweventrange{RangeName=“testrange”,RangeDescription=“test”,capacity=5}
添加(范围);
model.Ranges=eventRanges;
db.Events.Add(模型);
db.SaveChanges();
返回视图();
}
公共行动结果事件()
{
返回视图(db.Events);
}
在事件操作中设置断点并计算查询时,范围不会保存到事件:

请注意,EF为eventrange模型创建的数据库确实保存了范围:


我做错什么了吗?

如果将
范围
属性标记为
虚拟
,该怎么办

public virtual ICollection<EventRange> Ranges { get; set; }
公共虚拟ICollection范围{get;set;}

成功了,谢谢!延迟加载似乎需要虚拟属性。