c# - How do I update the value of a complex object within another object? -
Considering the following two classes, which are representing tables in the database, I have a stack of MyClass I want to set the statetipe db has two predefined values.
public class MyClass {[Key] public int id {get; Set; } Public string name {get; Set; } [Datatype (datatype multiline text)] public string description {get; Set; } Public virtual status type type {get; Set; }} Public Class Statutes {Public Ent ID {get; Set; } Public virtual iconging & lt; MyClass & gt; Receive {myclasses; Set; } Datatype (datatype multiline text)] public string description {get; Set; }} is a third table (MyClass_StatusType) that does not represent by an entity that acts as more than one intermediary.
My code:
MyClass MC = New MyClass (); Mc.Description = "description"; McStatusType.Id = 3; Db.MyClasses.Add (MC); Var id = db.SaveChanges (); There is a record in my status with an ID of 3. When I run this code, I get an empty reference exception on StatusType.
What is the correct way to set this price in MyClass?
You receive exceptions due to access to StatusType in this line
< Code> mc.StatusType.Id = 3; MC is a new object and it does not have any statistic type defined.
1) The best way to correct this is to use the FK Field Statistic ID mc.StatusTypeId = 3; 2) But if you can not use this field then the second solution is the following: You should instead of setting the ID Set it to an existing type (of a non existing current type). Creates an additional goaltrip in DB to get static type object.
var status type = MyMethodToGetExistingStatusType (3); McStatusType = statusType; I do not know how you can get your type of examples but in the method MyMethodToGetExistingStatusType () you can handle it. I hope this will help you?
Comments
Post a Comment