How do I delete a related object with a 1 to 1 relationship in the Entity Framework? - asp.net-mvc-3

I'm using EF Model First and in my Employee class I have a Manager property with a 1 to 1 relationship to itself, the Employee class:
public partial class Employee
{
public Employee()
{
}
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual Employee Manager { get; set; }
}
Now, when I get an existing object from the database and change the manager with:
employee.Manager = otherEmployeeInstance;
Context.Entry(employee).State = System.Data.EntityState.Modified;
Context.SaveChanges();
It works just fine; however, if I want to remove the manager this will not work:
employee.Manager = null;
It looks to me that I first need to "load" the manager (Employee) instance into the context since this makes it work:
var dummyVar = employee.Manager.Id;
employee.Manager = null;
So the question is, what's the best (proper) way to remove a related object?

obviously, when you want to delete an entity of the one-to-one relationship, the EF doesn't allow to delete it without preparing it before. that is, removing any dependent entity information from that entity. Remember, we are using Relational Database system and any breaking relation without any coordination causes to anomaly and failure.
When you want to remove a relation, you can use this at your controller:
employee.Remove(Manager);//Automatically Removes Navigational Properties at both entities
db.SaveChanges();
Instead of this :
employee.Manager = null;

Related

How to persist a model when doing Create / Edit in MVC3 before saving it to the database?

basically I am talking about the thing what we had in ASP.NET, called ViewState.
Here is the example, to keep it simple, I have a model Employee:
public class Employee
{
public string EmployeeId { get; set; }
public string Name { get; set; }
public string Company { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
}
My company created records for employees with their EmployeeId, Name and Company.
The employee needs to enter (update) only his Phone number and Address.
When I present a form in Edit / or Create mode for employee to enter this information, EmployeeID, Name and Company outputted just as text, while Phone and Address are editable fields (Html.EditorFor), which allows to keep values entered in the Model object.
When this form is HTTP posted back, lets say, validation fails, and the form is presented to the user again to correct his input (View(model)).
However the values for EmployeeID, Name and Company are lost, since they were not defined as Html.EditorFor, like Phone and Address, and therefore are not preserved, when the submitted model is being passed again into the View.
How do I preserve (persist) in the Model those properties (that are not editable)?
Thank you.
Simply use Html.HiddenFor and store the values on the page. You could also use the mvc futures project and Html.Serialize it, but then you are mimicking viewstate when it's not necessary.

Entity Framework 4 and MVC 3 - Inheritence and Loading Derived Entities

I've got some common properties (CreatedBy, CreatedOn, UpdatedBy, UpdatedOn) for nearly all of my entities. I decided to have a BaseEntity with these properties and then have all of my other entities inherit from this one.
For example:
BaseEntity --> Question
BaseEntity --> Answer
Now how do I load questions from my model container?
There is no db.Questions or db.Answers any more. Just db.BaseEntities.
Specifically I want to load all questions by their subject - so normally I would say db.Questions.Where(q => q.Subject.Id.Equals(subjectId)).
How do I do this now?
Many thanks,
Pete
First, there are multiple types of inheritance mapping strategies that you can use to configure your database
Table per hierarchy (TPH) - this is used by default, so currently you get only one table in database
Table per type (TPT)
Table per concrete type (TPC)
You can also add sets of concrete types to your DbContext
public class MyDbContext : DbContext
{
public DbSet<Question> Questions { get; set; }
public DbSet<Answer> Answers { get; set; }
}
And the most important - I would prefere composition over inheritance in your place. This feels more natural
public class HistoryRecord
{
public User CreatedBy { get; set; }
public User UpdatedBy { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime UpdatedOn { get; set; }
}
and use it as complex type inside Question, Answer, etc
public class Question
{
public HistoryRecord HistoryRecord { get; set; }
}
Do not use a base class for this.
You'll end up with one entity set and have to use typeof(X).
Worst of all, this may break future inheritance of other entities, especially if some are table per type, some are table per hierarchy and some are mixtures of the two.
Instead, use partial classes to define a common interface with the aspect properties (CreatedBy, CreatedOn, UpdatedBy, UpdatedOn).
Edit: The base entity will also require a table with the PKs of all your entities in it.
This will cause the table to be unnecessarily large and may result in performance hits during queries and inserts.

Specified type member is not supported in linq to entities

Hi hope someone can help.
I have an EF4 context with 2 POCO based entities that map on to 2 tables in a legacy SQL2005 database. There are no relationships betwen the tables and no associations between the entity definitions in the context.
public class Venue
{
public Venue(){}
public string LocationCode {get;set;}
public string LocationName {get;set;}
}
public class Booking
{
public Booking(){}
public string LocationCode {get;set;}
public int EventReference {get;set;}
public Venue BookingVenue {get;set;}
public Event BookingEvent {get;set;}
}
public class Event
{
public Event(){}
public int EventReference {get;set;}
public DateTime EventStart {get;set;}
/* plus another 60 or so properties */
}
I can do a LINQ select from each individually but whenever I try and join between Event and Booking I get
The specified type member ‘BookingEvent’ is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
I've tried all the workarounds I can find across the web (there are no enums, calcualted properties, etc) and I'm more than a little frustrated now.
Help ?
Here's the query in question....
List<Booking> bookings = (from b in CalendarDB.Bookings
join e in CalendarDB.Events join b.EventReference on e.EventReference
select b).ToList();
Without the relationships in the model, I don't think EF can figure out what data to use to join on. Even though your Booking class has a BookingEvent property, EF doesn't just 'know' that it needs to join on the Event table based on Booking.EventReference. Because of that, any query which attempts to use those reference properties will fail.

Why does Linq need a setter for a 'read-only' object property?

I'm using a Linq DataContext.ExecuteQuery("some sql statement") to populate a list of objects
var incomes = db.ExecuteQuery<IncomeAggregate>(sqlIncomeStatement(TimeUnit));
The IncomeAggregate is an object I made to hold the result of the records of this query.
One of the properties of this object is YQM:
public int Year { get; set; }
public int Quarter { get; set; }
public int Month { get; set; }
public string YQM
{
get { return string.Format("Y{0}-Q{1}-M{2}", Year, Quarter, Month); }
}
... more properties
Everything compiles OK, but when it executes the Linq I get the following error:
Cannot assign value to member 'YQM'. It does not define a setter.
But clearly, I don't want to 'set' it.
Y, Q and M are provided by the query to the database. YQM is NOT provided by the query.
Do I need to change the definition of my object somehow?
(I've just started using Linq and I'm still getting up to speed, so it could be very simple)
Well, I finally wound up just making the setter private
public string YQM {
get
{
return string.Format("Y{0}-Q{1}-M{2}", Year, Quarter, Month);
}
private set { ;}
}
Seems to work.
Linq is assuming that the properties of this object are values to load from the database, and clearly it can't set the YQM property because it has no setter. Try making YQM a method instead:
public string YQM()
{
return string.Format("Y{0}-Q{1}-M{2}", Year, Quarter, Month);
}

Populate DTO from several queries

I have a DTO with 40+ properties. But in order to populate all properties I need to execute 4 separate queries. My first query is in charged of getting basic information. For each row returned I run 3 more queries based on the id's given from the main query (N+1 problem). I can set use eager loading but then I'm loading thousands of objects that I don't need.
Should I split my DTO and create a separate DTO for each query I run then link then tie them all together into a central DTO by id?
I was envisioning a final DTO like this.
public class FooDto
{
public string Foo { get; set; }
public string Bar { get; set; }
public FirstDto FirstQueryResults { get; set; }
public SecondDto SecondQueryResults { get; set; }
public ThirdDto ThirdQueryResults { get; set; }
}
Is there a better way of solving this? I'm using Oracle and NHibernate doesn't support multi criterias. Note that I am joining most of my data. The problem comes when I need to query data with a complete new set of criteria.
How about creating a VIEW that joins the data to give the 40 properties all in one go, and basing your DTO on that - whatever a DTO may be ;-)

Resources