Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.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#_Entity Framework - Fatal编程技术网

C# 如何在另一个对象中更新复杂对象的值?

C# 如何在另一个对象中更新复杂对象的值?,c#,entity-framework,C#,Entity Framework,给定以下两个类,它们表示数据库中的表,我想将MyClass的statustype设置为statustype DB中的两个预定义值之一 public class MyClass { [Key] public int Id { get; set; } public string Name { get; set; } [DataType(DataType.MultilineText)] public string Description { get; set;

给定以下两个类,它们表示数据库中的表,我想将MyClass的statustype设置为statustype DB中的两个预定义值之一

 public class MyClass
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    [DataType(DataType.MultilineText)]
    public string Description { get; set; }
    public virtual StatusType StatusType { get; set; }
   }

 public class StatusType
{
    public int Id { get; set; }
    public virtual ICollection<MyClass> MyClasses{ get; set; }
    DataType(DataType.MultilineText)]
    public string Description { get; set; }
}
my StatusType中有一条ID为3的记录。当我运行此代码时,StatusType上会出现一个空引用异常


在MyClass中设置此值的正确方法是什么?

由于在此行中可以访问StatusType,因此会出现异常

mc.StatusType.Id = 3;
mc是一个新对象,未定义StatusType

1)纠正此问题的最佳方法是使用FK字段StatusTypeId

mc.StatusTypeId = 3;
2)但如果不能使用此字段,另一种解决方案如下:

您不应该设置(不存在的StatusType的)Id,而应该将其设置为现有类型。这会额外往返到DB以获取StatusType对象

var statusType = MyMethodToGetExistingStatusType(3);
mc.StatusType = statusType;
我不知道如何获得类型的实例,但是在方法mymethodtogeteExistingStatusType()中,您可以处理这个问题


我希望这对您有所帮助?

您在MyClass中错过了FK。如果你加上

 Public int StatusTypeId {get;set;}
这将映射实体的FK。当前您只有一个导航属性

而不是做

  mc.StatusType.Id = 3
你就是这样

  mc.StatusTypeId = 3

这将使您无需从
StatusType
表中进行选择。这意味着更少的代码和更少的SQL server访问。

您忽略了EF FK约定,这会导致您有更多的SQL数据库访问和更多的代码。根本不需要MyMethodToGetExistingStatusType(3)。是的,完全不需要MyMethodToGetExistingStatusType()方法,但只是为了澄清,他可以得到他的对象。你说得对。如果他有FK,我也会建议使用FK,但由于某种原因,他没有这个FK。我将把这一点添加到我的答案中,以便让其他人明白。
  mc.StatusTypeId = 3