How to add to a collection in Entity Framework 4.1 - entity-framework-4.1

I'm trying to add an object to an IList entity but the runtime throws a 'Object reference not set to an instance of an object.' exception.
Here is my model:
public class Discussion
{
[Key]
public int DiscussionId { get; set; }
public string Title { get; set; }
public virtual List<Message> Messages { get; set; }
public virtual List<Tag> Tags { get; set; }
public Guid Guid { get; set; }
public string UrlTitle { get; set; }
}
and here is the problematic line:
newDiscussion.Messages.Add(newMessage);
Apparently newDiscussion.Messages is null. What am I doing wrong?
Mark

You should initialize any collections inside of the class's constructor.
public class Discussion
{
public Discussion()
{
Messages = new List<Message>();
Tags = new List<Tag>();
}
// ...
}

Related

Deserialize Json with varying dictionary size in unity

I am using newtonsoft.json in unity and trying to deserialize from an api endpoint.
I have my Json response set up kind of like this..
{}pattern_order
{}LB
{}LC
Actual end point:
{"key":"value","pattern_order":{"LB":{"A":[{"order":["A","G","X","D"],"style":"SK"},{"order":["D","X","D"],"style":"SK"}],"B":[{"order":["A","D","X","G","C"],"style":"SK"},{"order":["C","X","D"],"style":"SK"},{"order":["D","G","X"],"style":"AT"}]},"LC":{"A":[{"order":["A","D","X","G","C"],"style":"AT"},{"order":["C","X","D"],"style":"SK"}],"B":[{"order":["A","D","X","G","C"],"style":"AT"},{"order":["C","X","D"],"style":"SK"}]}}}
Here, LB and LC have a similar structure, but I want to add more objects inside pattern_order.
What is the best way to deserialize such a json in unity?
After removing the . that shouldn't be there as mentioned I just have put it into Json2csharp which results in
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class A
{
public List<string> order { get; set; }
public string style { get; set; }
}
public class B
{
public List<string> order { get; set; }
public string style { get; set; }
}
public class LB
{
public List<A> A { get; set; }
public List<B> B { get; set; }
}
public class LC
{
public List<A> A { get; set; }
public List<B> B { get; set; }
}
public class PatternOrder
{
public LB LB { get; set; }
public LC LC { get; set; }
}
public class Root
{
public string key { get; set; }
public List<string> levels { get; set; }
public PatternOrder pattern_order { get; set; }
}
From there it is actually a simple step:
public class Thingy
{
public List<string> order;
public string style;
}
public class Root
{
public string key;
public List<string> levels;
// HERE YOU GO!
public Dictionary<string, Dictionary<string, Thingy[]>> pattern_order;
}
and
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
You can rename Thingy (and all other classes) to whatever you want ;)

Self referencing loop detected serialization exception

This is my class:
public partial class Event
{
public Event()
{
this.Comments = new HashSet<Comment>();
this.Rates = new HashSet<Rate>();
this.RawDates = new HashSet<RawDate>();
}
public int ID { get; set; }
public string Title { get; set; }
public string Summary { get; set; }
public string SiteURL { get; set; }
public string ContactEmail { get; set; }
public string LogoURL { get; set; }
public int EventType_ID { get; set; }
public Nullable<int> Location_ID { get; set; }
public Nullable<System.DateTime> BegginingDate { get; set; }
public string nTrain { get; set; }
public string Content { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
public virtual Conference Conference { get; set; }
public virtual ICollection<Rate> Rates { get; set; }
public virtual ICollection<RawDate> RawDates { get; set; }
public virtual EventType EventType { get; set; }
public virtual Location Location { get; set; }
}
When I call web api post method, exception mentioned in the title is thrown in this line:
var response = await client.PostAsJsonAsync("api/event", event);
I added [JsonIgnore] above every virtual field in Event class. This time serialization worked, but ignored fields were not serialized, their value is null. I really need all information contained in Event object. How can I solve this problem?
Adding below configuration in WebAPIConfig.cs resolves the bug.
var json = config.Formatters.JsonFormatter;
//Below configuration to mandatory to resolve the Self referencing loop detected with
"Newtonsoft.Json.JsonSerializationException" ,
json.SerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
Circular referencing objects cannot be JSON serialized. I would recommend you using a view model in which you will include the properties you need and then have your action return this view model instead of the actual domain model.

Web Api won't serialize my Object Graph

I got two simple entities:
public class Ingredient : IEntity
{
public Ingredient()
{
Drinks = new List<Drink>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Drink> Drinks { get; set; }
}
public class Drink : IEntity
{
public Drink()
{
Ingridients = new List<Ingredient>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Ingredient> Ingridients { get; set; }
public string Approach { get; set; }
}
I get the following error:
Object graph for type 'Gudo.Core.Model.Ingredient' contains cycles and cannot be serialized if reference tracking is disabled.
I've tried using the JsonIgnore Attribute on the Drinks collection and I've tried using:
JsonSerializerSettings jsSettings = new JsonSerializerSettings();
jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
In my global.asax
Nothing works..
Please help.
Did you make sure to set this on the JSON formatter's serializer settings? This line should do it for you:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

Code First Object not properly instantiating

I have a class department inheriting from activeentity
public class ActiveEntity : Entity, IActive
{
public ActiveEntity()
{
IsActive = true;
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid Id { get; set; }
public bool IsActive { get; set; }
[Timestamp, ScaffoldColumn(false), DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Computed)]
public Byte[] Timestamp { get; set; }
[ScaffoldColumn(false)]
public string CreationUserId { get; set; }
[ScaffoldColumn(false)]
public string LastModifiedUserId { get; set; }
}
public class Department:ActiveEntity
{
public Department()
{
this.Address = new DepartmentAddress();
}
[StringLength(9),MinLength(9),MaxLength(9)]
public string Name { get; set; }
public Guid ManagerId { get; set; }
[UIHint("AjaxDropdown")]
public User Manager { get; set; }
public Guid? AddressId { get; set; }
public DepartmentAddress Address { get; set; }
public ICollection<OverheadRate> OverheadRates { get; set; }
}
I am just using annotations no Fluent API. The data saves to the data Sql Server 2008 just fine however the address object never gets instantiated, even though I have the context use the include
return c.Set<Department>().Include(d => d.Address).Include(d => d.Manager).Where(predicate);
The data is returned I run sql profiler and then run the query it returns the correct data.
Any thoughts or suggestions?
Remove instantiating the address (this.Address = new DepartmentAddress();) in the Department constructor. Instantiating navigation references in the default constructor is evil and has nasty side effects like these:
What would cause the Entity Framework to save an unloaded (but lazy loadable) reference over existing data?
EF 4.1 Code First: Why is EF not setting this navigation property?

Mapping complex tree object using fluent mappings in EF 4.1?

I need some assistance with how to properly mapping this structure in EF 4.1:
public class Menu: Entity
{
public string Title { get; set; }
public virtual ICollection<MenuItem> MenuItems { get; set; }
}
public class MenuItem: Entity
{
public string Icon { get; set; }
public string Text { get; set; }
public string Action { get; set; }
public string Controller { get; set; }
public string Parameters { get; set; }
public virtual MenuItemType Type { get; set; }
public virtual Guid? ContextMenuId { get; set; }
public virtual Menu ContextMenu { get; set; }
public virtual Guid? ParentMenuItemId { get; set; }
public virtual MenuItem ParentMenuItem { get; set; }
public virtual ICollection<MenuItem> ChildMenuItems { get; set; }
}
The Entity base class has the ID for the enitties and I also have a base mapping class that builds the mappings for the key. Here is what I have so far for the MenuItem class:
public class MenuItemMapping : EntityConfiguration<MenuItem>
{
public MenuItemMapping()
{
HasOptional(mi => mi.ParentMenuItem).WithMany(p => p.ChildMenuItems).HasForeignKey(mi => mi.ParentMenuItemId).WillCascadeOnDelete(false);
HasOptional(mi => mi.ContextMenu).WithMany().HasForeignKey(mi => mi.ContextMenuId).WillCascadeOnDelete(false);
}
}
My concern is in the ContextMenu because it is a Menu type and not sure the best way to handle this type o mapping.
Update
Well, I added an additional mapping for the Menu (in a MenuMapping class similar to the above mapping class) for the collection of Menuitems and it seems to be OK, but I'd still like to know if what I am doing is correct.
Apparently, my mappings were fine. I thought I would have issues with circular references.