Entity Framework code first - cant add new class - entity-framework-4.1

I'm using code first and I set up my enviernment and all was well. Problem is I'm comming back later and needed to add a new class (Foo) e.g.
public class NorthwindContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
...
public DbSet<Foo> Foos { get; set; } // added
}
public class Foo // added
{
public string FooID { get; set; }
public int Payload { get; set; }
}
public class Customer
{
...
However now whenever I try to update my service reference I get an error. If I take out the
public DbSet<Foo> Foos { get; set; }
All is well except there are no Foos in the generated code. What I'm I missing?

You have few options to resolve the problem. Remove the IncludeMetadataConvention included in your context. Then manually delete the database.
public class NorthwindContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
public DbSet<Foo> Foos { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
base.OnModelCreating(modelBuilder);
}
}
or set the initializer in your programs entry point.
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<NorthwindContext>());
Final option would be to use Code First Migrations which is still in beta.

Related

.Net Core: controlling Json generated by Controller.Json method

By default, Controller.Json generates JSON for each public member of a class. How can I change this so that some members are ignored. Please note that I am using .Net Core.
Example:
[HttpGet("/api/episodes")]
public IActionResult GetEpisodes()
{
var episodes = _podcastProvider.Get();
return Json(episodes);
}
Thanks.
You can use [JsonIgnore] attribute that available in Newtonsoft.Json namespace like below:
public class Model
{
public int Id { get; set; }
public string Name { get; set; }
[JsonIgnore]
public int Age { get; set; }
}
How can I change this so that some members are ignored?
Under the covers this uses Newtonsoft.Json. There are two ways you can do this.
Use the JsonIgnore attribute and mark the properties you want omitted.
Have your episodes class define itself as "opt-in", meaning only properties marked with JsonProperty are serialized. [JsonObject(MemberSerialization.OptIn)]
It depends on the number of properties you need omitted versus serialized.
public class Episode
{
public int Id { get; }
[JsonIgnore] public string Name { get; }
[JsonIgnore] public Uri Uri { get; }
[JsonIgnore] public long Length { get; }
}
The above will yield the same JSON as this:
[JsonObject(MemberSerialization.OptIn)]
public class Episode
{
[JsonProperty]
public int Id { get; }
public string Name { get; }
public Uri Uri { get; }
public long Length { get; }
}

How to add to a collection in 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>();
}
// ...
}

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?

2 Objects of same type mapping to MySQL DB problem

public class Purchase {
public Address to { get; set; }
public Address from { get; set; }
}
public class Address {
public string name { get; set; }
}
I have 1 Purchase with 2 Address. How this should be on the Database (mySql) including foreign keys to be used on Entity Framework.
I have the problem that entity understands (based on fk) that Navigability in Address is 1 to many (*) and I don't have a list of Address on Purchase, i have defined 2.
Thanks,
Bart.
You can configure relationships of the tables.Build your model like this,
public class PurchaseConfiguration : EntityTypeConfiguration<Purchase >
{
public PurchaseConfiguration()
{
HasRequired(p=>p.to ).WithOptionalDependent().WillCascadeOnDelete(false);
HasRequired(p => p.from ).WithOptionalDependent().WillCascadeOnDelete(false);
}
}
and your db context you can add the configurations like this,
public class yourDbContext:DbContext
{
public DbSet<Purchase> Purchases{ get; set; }
public DbSet<Address> Addresses{ get; set; }
//other db sets here..
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new PurchaseConfiguration ());
// you can add configurations for other tables
}
}

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.