I have the following two classes that are able to internally track all changes.
public class Agent
{
public int AgentId { get; set; }
public ICollection Roles { get; set; }
public ICollection DeletedCollectionItems { get; set; }
public ICollection NewCollectionItems { get; set; }
ChangeTrackingState State { get; set; }
....
}
public class Role
{
public int RoleId { get; set; }
public ICollection Agents { get; set; }
public ICollection DeletedCollectionItems { get; set; }
public ICollection NewCollectionItems { get; set; }
ChangeTrackingState State { get; set; }
...
}
1) When an navigation property is set if it was previously set then the original object is added to DeletedCollectionItems and the new object is added to NewCollectionItems.
2) When objects are added or deleted from a collection they also update the relevant collection e.g. when a role is removed from Agent.Roles the role is added to DeletedCollectionItems.
My problem is:
Using EF in a disconnected environment I have to 'replay' all the changes when I attach my root entity (Agent) back to the context. If I'm updating an existing Agent and I've removed a role how can I recreate the relationship that is currently in the database and delete it so that the change is reflected in the database when I call SaveChanges?
I need to do this in a generic way so that I'm not duplicating code and can simply pass and object as the root object. I have based my implementation of Julie Lerman's ApplyChanges method
private static void ApplyChanges<TEntity>(TEntity root)
where TEntity : class, IObjectWithState
{
using (var context = new GeniusContext())
{
if (root.IsNew)
{
context.Set<TEntity>().Add(root);
}
else
{
context.Set<TEntity>().Attach(root);
}
foreach (var entry in context.ChangeTracker
.Entries<IObjectWithState>())
{
IObjectWithState stateInfo = entry.Entity;
entry.State = ConvertState(stateInfo.State);
}
context.SaveChanges();
}
}
Related
I have simple Model defined as
public class Project
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int StatusId { get; set; }
public virtual Status Status { get; set; }
}
public class Status
{
public int Id { get; set; }
public string Name { get; set; }
}
So, currently If I try to create a new Project Entity with breeze, it initializes the navigation property "Status" with null. How can I initialize it with default value? Note that, I don't want any binding with drop down field for this field at least for create operation.
function createNewProject() {
return manager.createEntity('Project');
}
You can define a custom constructor for the Project entity type and set a default StatusId value in there. The Status navigation property will be set to the relevant status entity (assuming the entity is in the breeze cache). For example:
function Project() {
this.StatusId = desiredDefaultStatusEntityId;
}
var manager = new breeze.EntityManager('...');
manager.metadataStore.registerEntityTypeCtor('Project', Project);
Take a look at Extending entities for some more information on extending entities.
I use Asp.Net MVC, Entity Framework. I have a form it looks like below.
Here, dropdownlist is filled from a table(types). Checkboxes is filled from another table(test). Tables are like below:
public class Types
{
public int TypesID{get;set;}
public string TestName { get; set; }
public string TestExplanation { get; set; }
public int TestTime { get; set; }
}
public class Tests
{
public int TestID{get;set;
public string Name { get; set; }
public string Code { get; set; }
}
public class Types_Tests
{
public int Types_TestsID{ get; set; }
public int TypesID { get; set; }
public int TestsID { get; set; }
public virtual Types Types { get; set; }
public virtual Tests Tests { get; set; }
}
Types_test table is relation table between Types and Tests. When I click Kaydet button, it shuld save type and checked tests. I made this operation using ViewBag, javascript and hdnvalue.I added checked checkboz values to a hdntext. I made saving process like below:
[HttpPost]
public ActionResult Index(string drpType, string hdntesttypes)
{
var TypeList = Types.GetAll();
ViewBag.TypesList = new SelectList(TypeList, "Id", "Name");
var testypeList = testTypes.GetAll();
ViewBag.TestTypesList = new SelectList(testypeList, "Id", "TestName");
GenericRepository<TestDisabledTypes> testDisabledRepository = new GenericRepository<TestDisabledTypes>(_context);
if (!string.IsNullOrEmpty(hdntesttypes))
{
string[] disabletypesArray = hdntesttypes.Split(',');
using (TransactionScope trns = new TransactionScope())
{
for (int i = 0; i < disabletypesArray.Length; i++)
{
Test_Types types = new Test_Types ();
types.TestTypesID = Convert.ToInt32(disabletypesArray[i]);
types.TypesID = Convert.ToInt32(drpType);
testDisabledRepository.Insert(types);
}
trns.Complete();
}
}
return View();
}
It wokrs. But I search better solution for this process. Can someone give me any idea?
Thanks.
If you don't need additional attributes for your entity class, you don't need create link table.
Just define the following class, and EF will generate the link table for you automatically.
public class Type
{
public int TypesID{get;set;}
public string TestName { get; set; }
public string TestExplanation { get; set; }
public int TestTime { get; set; }
public ICollection<Test> Tests { get; set; }
}
public class Test
{
public int TestID{get;set;
public string Name { get; set; }
public string Code { get; set; }
public ICollection<Type> Types {get;set;}
}
Well, in EntityFramework if you want to create a many to many relation object you need to create new object of "linking" entity. Unfortunately, it is not possible to add first object, add second object and say "Guys, you are in many to many relationships. Are you happy then?" :) You need to create relation object, set appropriate fields in it (I think these are ids of two objects itself) and add it to relation collection (entity) in your model. But before doing so you need to be sure that objects with data you are linking with are already exists in database. Otherwise you'll get an error
Also it's not necessary to create manually transaction because EF does it for you automatically each time you get/save your data
Can someone explain to me how to use multiple models with a single view in which each of the models represent a DB table?
What I've currently done is created a model file for each model.
Example Model:
[Table("Order")]
public class OrderModel
{
[Key, Column(Order = 0)]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int OrderID { get; set; }
[Key, Column(Order = 1)]
public int UserID { get; set; }
public UserProfile Account { get; set; }
public DateTime Date { get; set; }
public int ShipLocation { get; set; }
public string PONumber { get; set; }
public int StatusID { get; set; }
public StatusModel Status { get; set; }
}
Here is the other model that encompases all the models to use in a single controller / view.
public class OrderPlacementModel
{
public OrderModel OrderChild { get; set; }
public OrderItemsModel OrderItemsChild { get; set; }
public StatusModel StatusChild { get; set; }
public MaterialsModel MaterialsChild { get; set; }
public CategoryModel CategoryChild { get; set; }
public PackModel PackChild { get; set; }
}
public ActionResult PlaceOrder()
{
var viewModel = new OrderPlacementModel
{
OrderChild = new OrderModel(),//or fetch this object from your data source
OrderItemsChild = new OrderItemsChild(),
//...etcetera
};
return View(viewModel);
}
Edit
Or, if you've strongly typed your view to a List<OrderPlacementModel> instead of a single instance, you could do something similar to this:
public ActionResult PlaceOrder()
{
var viewModel = new List<OrderPlacementModel>();
var model = new OrderPlacementModel
{
OrderChild = new OrderModel(),//or fetch this object from your data source
OrderItemsChild = new OrderItemsChild(),
//...etcetera
};
viewModel.Add(model);
//lather, rinse, repeat for however many instances you need to send to your view.
return View(viewModel);
}
Ideally, you should create a view model for the view that encompasses the fields from each model that you need to expose via the view. You can then map these in your controller. I would keep your mapping classes completely ignorant of your view models. Keep your views independent of your data model.
public class OrderViewModel
{
public int OrderId { get; set; }
public int UserId { get; set; }
public DateTime Date { get; set; }
public int ShippingLocation { get; set; }
public List<ItemViewModel> Items { get; set; }
}
public class ItemViewModel
{
public int ItemId { get; set; }
public int Title { get; set; }
}
Note how I have created a view model for the order and - to allow the order have multiple items - have separated these out into a separate model class. Now, you can type your view to OrderViewModel and use as many instances of ItemViewModel as your require.
You can then map your viewmodels to database entities from your controller:
[HttpPost]
public ActionResult ConfirmOrder (OrderViewModel model)
{
if (ModelState.IsValid)
{
foreach (ItemViewModel item in model.Items)
{
/* Create instance of OrderItemsModel (or whatever your
DB mapping class is), populate with appropriate data
from 'item' and commit to database. */
}
OrderModel order = new OrderModel();
order.OrderId = model.OrderId;
order.UserId = model.UserId;
order.Date = model.Date;
order.ShipLocation = model.ShippingLocation;
/* TODO: Commit new order to database */
}
}
Doing things this way adds a little overhead to your initial development time but allows you a great deal more flexibility as you aren't forced to mould all of your views to the shape of your entity classes.
I'm using ASP.NET MVC4 EF CodeFirst.
Need help to write LINQ (to entities) code in Index action to get collection of Courses which are attended by selected student. The relationship is many to many with join table with payload.
//StudentController
//-----------------------
public ActionResult Index(int? id)
{
var viewModel = new StudentIndexViewModel();
viewModel.Students = db.Students;
if (id != null)
{
ViewBag.StudentId = id.Value;
// *************PROBLEM IN LINE DOWN. HOW TO MAKE COURSES COLLECTION?
viewModel.Courses = db.Courses
.Include(i => i.StudentsToCourses.Where(t => t.ObjStudent.FkStudentId == id.Value));
}
return View(viewModel);
}
The error I got is:
The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.
I have modeles (the third one is for join table with payload):
//MODEL CLASSES
//-------------
public class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
public virtual ICollection<StudentToCourse> StudentsToCourses { get; set; }
}
public class Course
{
public int CourseId { get; set; }
public string Title { get; set; }
public virtual ICollection<StudentToCourse> StudentsToCourses { get; set; }
}
public class StudentToCourse
{
public int StudentToCourseId { get; set; }
public int FkStudentId { get; set; }
public int FkCourseId { get; set; }
public string Classroom { get; set; }
public virtual Student ObjStudent { get; set; }
public virtual Course ObjCourse { get; set; }
}
Then, here is modelview I need to pass to view
//VIEWMODEL CLASS
//---------------
public class StudentIndexViewModel
{
public IEnumerable<Student> Students { get; set; }
public IEnumerable<Course> Courses { get; set; }
public IEnumerable<StudentToCourse> StudentsToCourses { get; set; }
}
EF does not support conditional include's. You'll need to include all or nothing (ie no Whereinside the Include)
If you need to get the data for just certain relations, you can select it into an anonymous type, something like (the obviously untested);
var intermediary = (from course in db.Courses
from stc in course.StudentsToCourses
where stc.ObjStudent.FkStudentId == id.Value
select new {item, stc}).AsEnumerable();
Obviously, this will require some code changes, since it's no longer a straight forward Course with a StudentsToCourses collection.
I'm trying to insert a new Entity in EF:
public class Ad
{
// Primary properties
public int Kms { get; set; }
// Navigation properties
public virtual Model Model { get; set; }
}
And I receive from the View the model like this (example values):
kms = 222
Model.Id = 3
Then when I do the Add and SaveChanges of the Entity Framework, I get a NULL record inserted in the Model Table (that generated a new ID) and a record in the Ad Table with the new inserted Model Id.
Why is this happening?
Service Layer:
public void CreateAd(CreateAdDto adDto)
{
var adDomain = Mapper.Map<CreateAdDto, Ad>(adDto);
_adRepository.Add(adDomain);
_adRepository.Save();
}
Repository:
public void Add(T entity)
{
_dbSet.Add(entity);
}
public void Save()
{
try
{
_dataContext.SaveChanges();
}
catch (DbEntityValidationException e)
{
var s = e.EntityValidationErrors.ToList();
throw;
}
}
ViewModel:
public class CreateAdViewModel
{
// Primary properties
public string Version { get; set; }
public int Kms { get; set; }
public int Year { get; set; }
public decimal Price { get; set; }
public int Make_Id { get; set; }
public int Model_Id { get; set; }
// Navigation properties
public IEnumerable<SelectListItem> MakeList { get; set; }
public IEnumerable<SelectListItem> ModelList { get; set; }
}
Dto:
public class CreateAdDto
{
// Primary properties
public int Kms { get; set; }
public int Model_Id { get; set; }
}
The Mapping:
Mapper.CreateMap<CreateAdDto, Ad>().ForMember(dest => dest.Model, opt => opt.MapFrom(src => new Model { Id = src.Model_Id }));
If you just call the Add method on the Ad instance, all the related entities are treated as new entities. Therefore you can attach the Model instance first and add the Ad.
context.Models.Attach(ad.Model);
context.Ads.Add(ad);
context.SaveChanges();
SOLUTION BASED ON #Eranga Answer (thanks man!)
Hope this can help somebody else as it help me thanks to #Eranga.
What it was happening is that in the Mapping from DTO to DOMAIN, the Model entity was maping from an Model_Id coming from a Dropdownlist in the View to an Entity Model (as you can see in the mapping line in the question).
Then, when it was added to the database trough Entity Framework, the EF was not aware of the existence of the Model navigation property in the Ad Domain Entity.
So what I had to create to solve this was adding a new method to my repository to handle the possibility to attach the Model Entity to the Ad Entity context:
public void Attach(T entity)
{
_dbSet.Attach(entity);
}
and ad the attach in the Ad Service Create method:
private readonly IRepository<Ad> _adRepository;
private readonly IRepository<Search> _searchRepository;
private readonly IRepository<Model> _modelRepository;
public AdService(IRepository<Ad> adRepository, IRepository<Search> searchRepository, IRepository<Model> modelRepository)
{
_adRepository = adRepository;
_searchRepository = searchRepository;
_modelRepository = modelRepository;
}
public void CreateAd(CreateAdDto adDto)
{
var adDomain = Mapper.Map<CreateAdDto, Ad>(adDto);
_modelRepository.Attach(adDomain.Model);
_adRepository.Add(adDomain);
_adRepository.Save();
}
So now, when the adDomain object arrives to the EF trough the _adRepository.Add, it already knows about the existence of the navigation property Model, and can add the new adDomain ojbect.
Before, what it was happening is that, when the adDomain object was arriving at the EF, the EF was not aware of the Model existence so it was creating an null record.
Hope this help anybody else.
Regards.