Monday, April 23, 2012

Creating Many-2-Many reference with EF

In my current project (which is really small) i have 3 tables/POCO entities which i would like to manipulate using EF.



The Tables are:




  1. Status (contains status details)

  2. StatusStatusType (which is needed because of the many-2-many relationship)

  3. StatusType (A table which is used to group statuses by type)



I now want to create a new Status in the database and user code like you see below



//Create new status (POCO) entity
var newStatus = new Status {
StatusId = status.Id,
UserId = user.Id,
Text = status.text,
CreateDate = DateTime.Now
};

// Persist need status to database
using (var db = new demoEntities())
{
db.Statuses.AddObject(newStatus);
db.SaveChanges();
}


This code works fine but i want to also set StatusType of the status entity. All possible status types are already included in the StatusType table. I don't want to create new statuses only create a reference.



I figured i should use something like :



status.StatusTypes == "new";




No comments:

Post a Comment