Update hierarchy model in Entity Framework - asp.net-mvc

I have two model classes:
Request:
public partial class Request
{
public long Id { get; set; }
public string Username { get; set; }
public string Description { get; set; }
public System.DateTime CreateDate { get; set; }
public long DeviceId { get; set; }
public bool IsFinalized { get; set; }
public Nullable<long> ParentId { get; set; }
public virtual Device Device { get; set; }
}
Device:
public partial class Device
{
public Device()
{
this.Requests = new List<Request>();
}
public long Id { get; set; }
public string Serial { get; set; }
public string AssetNumber { get; set; }
public System.DateTime CreatedDate { get; set; }
public virtual ICollection<Request> Requests { get; set; }
}
I have to update the models I use this method
public void Update(RequestViewModel viewModel)
{
var entity = _mappingEngine.Map<Request>(viewModel);
_requests.Attach(entity);
_uow.Entry(entity).State = EntityState.Modified;
}
but only Request model is updated after calling the Update method. I want to update both models. Please help me.

Attaching an entity to a DbContext, mark the attached entity and all its dependencies (i.e. associated entities) UnChanged. So its you who must tell EF what entities are new and what entities were modified.

Related

Rename column in derived class using Entity Framework

I have asked question in a different post, but seems that was not the right question, so going to reword here:
I have three classes:
public class StateLog : BaseModel
{
public Guid StateLogId { get; set; }
public Guid LookupMasterId { get; set; }
public Guid EntityId { get; set; }
public string Discriminator { get; set; }
public bool IsActive { get; set; }
public virtual LookupMaster State { get; set; }
}
Second class:
public class ApplicationState : StateLog
{
[Column("EntityId")]
public Guid ApplicationId { get; set; }
}
There is another Class DocumentStates which inherits from StateLog.
Application:
public class Application : BaseModel
{
public Guid ApplicationId { get; set; }
public Guid UserId { get; set; }
public virtual User User { get; set; }
[Required]
public Guid ApplicationTypeId { get; set; }
public bool? AuthorizedToWork { get; set; } = false;
public string Token { get; set; }
public string ApplicationTitle { get; set; }
public string WorkStartDate { get; set; }
public Nullable<DateTime> SignedAt { get; set; } = DateTime.Now;
public bool? Signed { get; set; }
public string Notes { get; set; }
public virtual ICollection<ApplicationSelfDeclaration> ApplicationSelfDeclarations { get; set; }
public virtual ICollection<ApplicationState> ApplicationStates { get; set; }
public virtual ICollection<StateLog> StateLogs { get; set; }
}
I am trying to save statelogs for both application and documents in same table and based on Discriminator, fetch data.
E.g.
_context.Applications.include(a => a.ApplicationState)
This is not not working. ApplicationState should Alias EntityId column as ApplicationId. But it is not working.
Any idea what my options are at this point?
Thanks in advance.

ViewModel for multiple tables without links between tables

I'm trying to write a View Model in an ASP.NET MVC5 project to show data from different tables on a form that the user can then edit and save. I'm using the following :-
VS 2017, c#, MySQL Database, Entity Framework 6.1.3, MySQL Connector 6.9.9, Code First from Database (existing database that I can't change)
To complicate matters, there are no links between the tables in the database, so I cannot work out how to create a suitable View Model that will then allow me to save the changes.
Here are the 4 table models :-
public partial class evc_bearer
{
[Key]
[Column(Order = 0]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long evcid { get; set; }
[Key]
[Column(Order = 1]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long bearerid { get; set; }
public int vlan { get; set; }
[Column("ref")]
public string _ref { get; set; }
[Required]
public string port { get; set; }
[Required]
public string endpoint { get; set; }
}
public partial class bearer
{
[Key]
public long id { get; set; }
[Column("ref")]
[Required]
public string _ref { get; set; }
public string name { get; set; }
public long? site { get; set; }
public long? provider { get; set; }
public long? mtu { get; set; }
public float? rental { get; set; }
public int? offsiteprovider { get; set; }
public float? offsiteproviderrental { get; set; }
public bool? aend { get; set; }
public int? equipmentport { get; set; }
public string orderref { get; set; }
public string offsiteref { get; set; }
public string notes { get; set; }
public float? bookingfactor { get; set; }
}
public partial class evc
{
[Key]
public long id { get; set; }
[Required]
public string type { get; set; }
public byte servicetype { get; set; }
public byte cos { get; set; }
public int cir { get; set; }
public int pir { get; set; }
public bool burst { get; set; }
[Column("ref")]
public string _ref { get; set; }
public string orderref { get; set; }
public byte state { get; set; }
public string notes { get; set; }
public float? rental { get; set; }
}
public partial class evc_provider
{
[Key]
public long id { get; set; }
[Required]
public string provider { get; set; }
}
This is the View Model I tried writing :-
public partial class evcBearersVM
{
[Key]
[Column(Order = 0)]
public long evcid { get; set; }
[Key]
[Column(Order = 1)]
public long id { get; set; }
[Column("ref")]
public string b_ref { get; set; }
public string b_name { get; set; }
public string ep_provider { get; set; }
public int eb_vlan { get; set; }
public string eb_port { get; set; }
public string eb_endpoint { get; set; }
}
This is the Linq query I used to populate the View Model :-
IQueryable<evcBearersVM> data = from eb in csdb.evc_bearers
join b in csdb.bearers on eb.bearerid equals b.id
join ep in csdb.evc_providers on b.provider equals ep.id
join e in csdb.evcs on eb.evcid equals e.id
where (eb.evcid == evcid && b.id == id)
select new evcBearersVM
{
evcid = eb.evcid,
id = b.id,
b_ref = b._ref,
b_name = b.name,
ep_provider = ep.provider,
eb_vlan = eb.vlan,
eb_port = eb.port,
eb_endpoint = eb._ref
};
So the query works and joins the tables to get the data I need and I can display this date in various views as needed. What I now need to do is be able to edit a row and save it back to the database. I have an Edit View that is showing the data I need but I'm not sure how to save changes given that it's a View Model and the DB Context isn't aware of it. Grateful for any help.
What you should do is, use the same view model as your HttpPost action method parameter and inside the action method, read the entities you want to udpate using the Id's (you can get this from the view model, assuming your form is submitting those) and update only those properties you need to update.
[HttpPost]
public ActionResult Edit(evcBearersVM model)
{
var b = csdb.bearers.FirstOrDefault(a=>a.id==model.id);
if(b!=null)
{
b.name = model.b_name;
b._ref = model.b_ref;
csdb.SaveChanges();
}
// Update the other entity as well.
return RedirectToAction("Index");
}

Breeze.js and PreserveReferencesHandling serializing failure

I encounter a problem with deserializing entities in client side with breeze.js.
My data model entity has one to many relation to other entities (A has ICollection of B)
When I make a query , I see the data returned from the server include $ref= # , I understood breeze uses this to identify same objects returned from the server.
But in client side all those entities with $ref=# doesn't deserialized properly I get this function () { return mc.refMap[node]} insted to get the real object in client side .
Here is my object structure :
public partial class Product
{
public Product()
{
this.ProductCatalogue = new HashSet<ProductCatalogue>();
this.DiameterRanges = new HashSet<DiameterRanges>();
this.Product_Children = new HashSet<Product>();
}
public int Id { get; set; }
public string Code { get; set; }
public virtual ICollection<ProductCatalogue> ProductCatalogue { get; set; }
public virtual ICollection<DiameterRanges> DiameterRanges { get; set; }
public virtual Product Product_Parent { get; set; }
}
public partial class DiameterRanges
{
public int Id { get; set; }
public double MinSPH { get; set; }
public double MaxSPH { get; set; }
public double MinCyl { get; set; }
public double MaxCyl { get; set; }
public short MinDiameter { get; set; }
public short MaxDiameter { get; set; }
public int Product_Id { get; set; }
public virtual Product Product { get; set; }
}
Nothing special in my server side query : Context.Product.Include("DiameterRanges");
Any idea to figure out this problem .
Thanks in advance ....

Create object with many-to-many relationship in MVC 4

I am using MVC 4 with EF code first approach. I have two simple objects. These are their POCO classes:
public class Activity
{
//Primitive Properties
[HiddenInput]
public int Id { get; set; }
[Required]
public int LengthInMinutes { get; set; }
public string AdditionalInfo { get; set; }
[Required]
public bool Archive { get; set; }
//Navigation Properties
public virtual User User { get; set; }
public virtual ActivitySet ActivitySet { get; set; }
public virtual ICollection<Company> Companies { get; set; }
public virtual ICollection<Description> Descriptions { get; set; }
}
public class Company
{
//Primitive Properties
[HiddenInput]
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public bool Archive { get; set; }
//Navigation Properties
public virtual ICollection<Activity> Activities { get; set; }
}
So there is a many-to-many relationship between Activity and Company entities. I am creating new Activity in my repository class, but when I assign a Company for the Activity like so:
activity.Companies.Add(company);
I get NullReference exception. I had a look around but according to this link:
BuildStarted.com
my approach seems to be right.
Why doesn't it work???
Before you can use Add() off Companies, it needs to be initialized.
activity.Companies = new List<Company>();
You could also initialize that in the contructor of Activity.
public class Activity
{
public Activity()
{
Companies = new List<Company>();
Descriptions = new List<Description>();
}
//Primitive Properties
[HiddenInput]
public int Id { get; set; }
[Required]
public int LengthInMinutes { get; set; }
public string AdditionalInfo { get; set; }
[Required]
public bool Archive { get; set; }
//Navigation Properties
public virtual User User { get; set; }
public virtual ActivitySet ActivitySet { get; set; }
public virtual ICollection<Company> Companies { get; set; }
public virtual ICollection<Description> Descriptions { get; set; }
}

MVC - Entity framework - Metadata relation

Today I've been working with MVC for the first time. Also normally I use the EF with model first, but I wanted to try POCO.
So I've made my 3 entities and when I try to make a controller I get an error:
Unable to retrieve metadata for "BookExchange.Models.Exchange". Unable to determine the principal end of an association between the types "BookExchange.Models.Exchange" and "BookExchange.Models.Book". The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
My 3 classes:
public class Book
{
public int BookID { get; set; }
public string Name { get; set; }
public string Author { get; set; }
public string ISBN10 { get; set; }
public int PersonID { get; set; }
public virtual Person Person { get; set; }
public virtual Exchange Exchange { get; set; }
}
public class Person
{
public int PersonID { get; set; }
public string Name { get; set; }
public virtual ICollection<Book> Books { get; set; }
public virtual ICollection<Exchange> Exchanges { get; set; }
}
public class Exchange
{
[Key]
public int BookID { get; set; }
public int PersonID { get; set; }
public DateTime ReturnDate { get; set; }
public virtual Person Person { get; set; }
public virtual Book Book { get; set; }
}
Does anyone know what I'm doing wrong? I don't want to lose the association properties.
Thanks in advance!
Try adding foreign key properties for your references. E.g.
public class Book
{
public int BookID { get; set; }
public string Name { get; set; }
public string Author { get; set; }
public string ISBN10 { get; set; }
public virtual Person Person { get; set; }
public int PersonID { get; set; }
public virtual Exchange Exchange { get; set; }
public int ExchangeID { get; set; }
}
public class Person
{
public int PersonID { get; set; }
public string Name { get; set; }
public virtual ICollection<Book> Books { get; set; }
public virtual ICollection<Exchange> Exchanges { get; set; }
}
public class Exchange
{
public int ExchangeID { get; set; }
public int BookID { get; set; }
public virtual Book Book { get; set; }
public int PersonID { get; set; }
public virtual Person Person { get; set; }
public DateTime ReturnDate { get; set; }
}
Also, take a look at ScottGu's post on code first and this EF post on conventions.
Try this: (Remove database, so EF will create new)
public class Book
{
public int Id { get; set; }
public string Name { get; set; }
public string Author { get; set; }
public string ISBN { get; set; }
public virtual Person Person { get; set; }
public virtual Exchange Exchange { get; set; }
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Book> Books { get; set; }
public virtual ICollection<Exchange> Exchanges { get; set; }
}
public class Exchange
{
public int Id { get; set; }
public DateTime ReturnDate { get; set; }
public virtual Person Person { get; set; }
public virtual Book Book { get; set; }
}
It's your one on one associations.
Remove one reference between exchange or book, so Code-first can decide which one is more important in your one on one relation (Book <--> Exchange)
If you want to know why, you should read this:

Resources