I have 3 tables,
1. AttributeTypes (Columns: AttributeId (PK), AttributeName, ..)
2. Location (Columns: locationId (PK), LocationName, ...)
3. LocationAttributeType (Columns: locationId (FK), AttributeId (FK))
Whenever I am trying to insert new location record along with its attribute type from GUI, it should create new record for Table- Location and LocationAttributeType. But EF trying to add new record in Table- AttributeTypes as well, which is just used as reference table and should not add new/duplicate records in it. How can I prevent that?
here is my code,
The model which GUI sends is,
public class LocationDataModel
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Code { get; set; }
[DataMember]
public List<AttributeTypeDataModel> AssignedAttributes = new List<AttributeTypeDataModel>();
}
public class AttributeTypeDataModel
{
protected AttributeTypeDataModel() {}
public AttributeTypeDataModel(int id) { this.Id = id; }
public AttributeTypeDataModel(int id, string name)
: this(id)
{
this.Name = name;
}
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public virtual ICollection<LocationDataModel> Locations { get; set; }
}
The Entities created by EF are,
public partial class Location
{
public Location()
{
this.AttributeTypes = new List<AttributeType>();
}
public Location(int campusId, string code)
: this()
{
CampusId = campusId; Code = code;
}
public int Id { get; set; }
public int CampusId { get; set; }
public string Code { get; set; }
public virtual ICollection<AttributeType> AttributeTypes { get; set; }
}
public partial class AttributeType
{
public AttributeType()
{
this.Locations = new List<Location>();
}
public int AttributeTypeId { get; set; }
public string AttributeTypeName { get; set; }
public virtual ICollection<Location> Locations { get; set; }
}
I have below code to Add these new location to database,
private IEnumerable<TEntity> AddEntities<TModel, TEntity, TIdentityType>
(IEnumerable<TModel> models, Func<TModel, TIdentityType> primaryKey,
IGenericRepository<TEntity, TIdentityType> repository)
{
var results = new List<TEntity>();
foreach (var model in models)
{
var merged = _mapper.Map<TModel, TEntity>(model);
var entity = repository.Upsert(merged);
results.Add(entity);
}
repository.Save();
return results.AsEnumerable();
}
I am using following generic repository to do entity related operations
public TEntity Upsert(TEntity entity)
{
if (Equals(PrimaryKey.Invoke(entity), default(TId)))
{
// New entity
return Context.Set<TEntity>().Add(entity);
}
else
{
// Existing entity
Context.Entry(entity).State = EntityState.Modified;
return entity;
}
}
public void Save()
{
Context.SaveChanges();
}
Whats wrong I am doing here?
The DbSet<T>.Add() method attaches an entire object graph as added. You need to indicate to EF that the 'reference' entity is actually already present. There are two easy ways to do this:
Don't set the navigation property to an object. Instead, just set the corresponding foreign key property to the right value.
You need to ensure that you don't load multiple instances of the same entity into your object context. After creating the context, load the full list of AttributeType entities into the context and create a Dictionary<> to store them. When you want to add an attribute to a Location retrieve the appropriate attribute from the dictionary. Before calling SaveChanges() iterate through the dictionary and mark each AttributeType as unchanged. Something like this:
using (MyContext c = new MyContext())
{
c.AttributeTypes.Add(new AttributeType { AttributeTypeName = "Fish", AttributeTypeId = 1 });
c.AttributeTypes.Add(new AttributeType { AttributeTypeName = "Face", AttributeTypeId = 2 });
c.SaveChanges();
}
using (MyContext c = new MyContext())
{
Dictionary<int, AttributeType> dictionary = new Dictionary<int, AttributeType>();
foreach (var t in c.AttributeTypes)
{
dictionary[t.AttributeTypeId] = t;
}
Location l1 = new Location(1, "Location1") { AttributeTypes = { dictionary[1], dictionary[2] } };
Location l2 = new Location(2, "Location2") { AttributeTypes = { dictionary[1] } };
// Because the LocationType is already attached to the context, it doesn't get re-added.
c.Locations.Add(l1);
c.Locations.Add(l2);
c.SaveChanges();
}
In this specific case you are using a many-to-many relationship, with EF automatically handling the intermediate table. This means that you don't actually have the FK properties exposed in the model, and my first suggestion above won't work.
Therefore, you either need to use the second suggestion, which still ought to work, or you need to forgo the automatic handling of the intermediate table and instead create an entity for it. This would allow you to apply the first suggestion. You would have the following model:
public partial class Location
{
public Location()
{
this.AttributeTypes = new List<LocationAttribute>();
}
public Location(int campusId, string code)
: this()
{
CampusId = campusId; Code = code;
}
public int Id { get; set; }
public int CampusId { get; set; }
public string Code { get; set; }
public virtual ICollection<LocationAttribute> AttributeTypes { get; set; }
}
public partial class LocationAttribute
{
[ForeignKey("LocationId")]
public Location Location { get; set; }
public int LocationId { get; set; }
public int AttributeTypeId { get; set; }
}
public partial class AttributeType
{
public int AttributeTypeId { get; set; }
public string AttributeTypeName { get; set; }
}
With this approach you do lose functionality since you can't navigate from a Location to an AttributeType without making an intermediate lookup. If you really want to do that, you need to control the entity state explicitly instead. (Doing that is not so straightforward when you want to use a generic repository, which is why I've focused on this approach instead.)
Thank you all for your suggestions.
I have to get rid of my generic repository here to save my context changes and do it manually as below,
private IEnumerable<int> AddLocationEntities(IEnumerable<LocationDataModel> locations)
{
var results = new List<int>();
foreach (LocationDataModel l in locations)
{
var entity = _mapper.Map<LocationDataModel, Location>(l);//you can map manually also
var AttributeCode = l.AssignedAttributes.FirstOrDefault().AttributeTypeId;
using (MyContext c = new MyContext())
{
var attr = c.AttributeTypes.Where(a => a.Id == AttributeTypeId ).ToList();
entity.AttributeTypes = attr;
c.Locations.Add(entity);
c.SaveChanges();
var locid = entity.Id;
results.Add(locid);
}
}
return results;
}
In the else statement of yourUpsert you should add
context.TEntity.Attach(entity);
Related
This is how database structure looks like:
Vehicle has lot of CanNetworks and each CanNetwork has lot of ECUs. And that would save perfectly if that was only I have.
But, each vehicle also has one special ECU called gatewayECU so problem happens with saving because entity framework core does not know how to handle that scenario. It needs to insert vehicle before inserting ecus, but how to insert vehicle when ecu is not inserted.
This is what I tried: ignore (delete, invalidate) gatewayecu field (column is nullable in database), then I insert whole graph and then update vehicle with gatewayEcuId field I stored in some variable before doing anything.
Solution is not pretty. How to handle this scenario.
public class Vehicle : BaseEntity
{
public Vehicle()
{
CANNetworks = new List<CANNetwork>();
}
public List<CANNetwork>? CANNetworks { get; set; }
public ECU? GatewayECU { get; set; } = default!;
public int? GatewayECUId { get; set; }
}
public class CANNetwork : BaseEntity
{
public CANNetwork()
{
ECUs = new List<ECU>();
}
public string Name { get; set; } = default!;
public ICollection<ECU>? ECUs { get; set; }
public int VehicleId { get; set; }
public Vehicle? Vehicle { get; set; } = default!;
}
public class ECU : BaseEntity
{
public int CANNetworkId { get; set; }
public CANNetwork? CANNetwork { get; set; } = default!;
}
This is ugly solution which I don't want:
public async Task<int> Insert(Vehicle vehicleDefinition, ECU vehicleGatewayECU)
{
var result = -1;
using (var transaction = _databaseContext.Database.BeginTransaction())
{
result = await Insert(vehicleDefinition);
if (vehicleGatewayECU != null)
{
var ecu = await _databaseContext.ECUs.FirstOrDefaultAsync(x => x.Name == vehicleGatewayECU.Name && vehicleDefinition.Name == x.CANNetwork.Vehicle.Name);
if (ecu != null)
{
vehicleDefinition.GatewayECUId = ecu.Id;
result = await Update(vehicleDefinition);
transaction.Commit();
return result;
}
}
else
{
transaction.Commit();
}
}
return result;
}
EDIT:
I am now thinking about changing table structure in a way to get rid of gatewayECU field on Vehicle, and put some flag IsGatewayEcu in ECU table
I have just started using AutoMapper on an asp net core project and I'm trying to map an object that has a collection of an object that also has a collection of an object to an entity.
The source
public class MyClass
{
public List<MyCollection> MyCollections { get; set; }
}
public class MyCollection
{
public int CollectionId { get; set; }
public List<Description> Descriptions { get; set; }
}
public class Description
{
public int DescriptionId { get; set; }
public string Text { get; set; }
}
The destination
public class DescriptionToCollection
{
public int DescriptionId { get; set; }
public int CollectionId { get; set; }
}
I've played around with ConvertUsing thinking something like this, but I can't make it work.
CreateMap<MyClass, List<DescriptionToCollection>>()
.ConvertUsing(source => source.MyCollections.Select(x =>x.Description.Select(y=> new DescriptionToCollection{ DescriptionId=y.DescriptionId,CollectionId=x.CollectionId}).ToList()
));
Searching AutoMappers docs and the internet, I couldn't find anything similar to my problem.
Any help is highly appreciated.
Besides a typo in your example code, you almost had it. Because you aren't mapping 1:1 at the top level, you need to flatten somewhere, and you do that using SelectMany, moving the ToList call appropriately.
CreateMap<MyClass, List<DescriptionToCollection>>()
.ConvertUsing(source => source.MyCollections.SelectMany(x => // SelectMany to flatten
x.Descriptions.Select(y =>
new DescriptionToCollection
{
DescriptionId = y.DescriptionId,
CollectionId = x.CollectionId
}
) // ToList used to be here
).ToList()
);
Try to implement ITypeConverter, follow the example code:
Your Classes
public class Class1
{
public List<Class2> class2 { get; set; }
}
public class Class2
{
public int CollectionId { get; set; }
public List<Class3> class3 { get; set; }
}
public class Class3
{
public int DescriptionId { get; set; }
public string Text { get; set; }
}
public class ClassDto
{
public int DescriptionId { get; set; }
public int CollectionId { get; set; }
}
The custom map
public class ClassCustomMap : ITypeConverter<Class1, List<ClassDto>>
{
public List<ClassDto> Convert(Class1 source, List<ClassDto> destination, ResolutionContext context)
{
var classDtoList = new List<ClassDto>();
foreach (var item in source.class2)
{
var collectionID = item.CollectionId;
foreach (var obj in item.class3)
{
var classDto = new ClassDto();
classDto.CollectionId = collectionID;
classDto.DescriptionId = obj.DescriptionId;
classDtoList.Add(classDto);
}
}
return classDtoList;
}
}
The mapping declaration
CreateMap<Class1, List<ClassDto>>().ConvertUsing<ClassCustomMap>();
How to use it
var class2 = new Class2();
class2.CollectionId = 2;
var class3 = new Class3();
class3.DescriptionId = 1;
class3.Text = "test";
class2.class3 = new System.Collections.Generic.List<Class3>() { class3 };
var class1 = new Class1();
class1.class2 = new System.Collections.Generic.List<Class2>() { class2 };
var result = mapper.Map<List<ClassDto>>(class1);
For clarity and to simplify I have used explicit cycles, if you want you can optimize the conversion function using LinQ and Lambda
You are missing the purpose of auto-mapper.
It should be used for transforming an input object of one type into an output object of a different type.
And you wanted to create a map from MyClass type to List - this should be treated as projection.
You can achieve that using LINQ (for example as a extension method on MyClass):
public static class MyClassExtension
{
public static List<DescriptionToCollection> ToDescriptionToCollection(this MyClass value)
{
return value.MyCollections.SelectMany(mc => mc.Descriptions.Select(d => new DescriptionToCollection()
{
CollectionId = mc.CollectionId,
DescriptionId = d.DescriptionId
})).ToList();
}
}
I have basic object models with cross references
//Model in which I pass and gather data from view
public class ItemModel
{
public BasicItem BasicItem;
public FoodItem FoodItem;
public LocalItem LocalItem;
public ItemModel()
{
BasicItem = new BasicItem();
FoodItem = new FoodItem();
LocalItem = new LocalItem();
}
}
//And classes represents EF entities
public class BasicItem
{
...//Multiple basic fields: int, string
//EF references for PK-FK connection
public FoodItem FoodItem { get; set; }
public LocalItem LocalItem { get; set; }
}
public class LocalItem
{
...//Multiple basic fields: int, string
//EF reference for PK-FK connection
public BasicItem BasicItem { get; set; }
}
public class FoodItem
{
...//Multiple basic fields: int, string
//EF reference for PK-FK connection
public BasicItem BasicItem { get; set; }
}
And my view in basics seems like this
#model ItemModel
...
<input required asp-for="BasicItem.Price" type="number" name="Price">
...
<input asp-for="FoodItem.Weight" type="number" name="Weight">
...
As now I connect it (so different entities have relation each to other) like this:
public async Task<IActionResult> ProductAdd(ItemModel ItemModel)
{
if (ItemModel.BasicItem != null)
{
if (ItemModel.LocalItem != null)
{
ItemModel.BasicItem.LocalItem = ItemModel.LocalItem;
ItemModel.LocalItem.BasicItem = ItemModel.BasicItem;
await db.LocalItems.AddAsync(ItemModel.LocalItem);
}
//same for FoodItem
await db.BasicItems.AddAsync(ItemModel.BasicItem);
await db.SaveChangesAsync();
}
}
But data from form dosent bind to my ItemModel, so my code fails at point when it trying to Add new entity to db, but it has null fields(which null by default, but setuped in form).
Is there any way I can help bind this model to data Im entering?
As other way I can only see this: create plain model which will have all fields from Basic, Local and Food items and bind it in my action. But it will hurt a much, if I ever wanted to change one of this classes.
For you scenario , BasicItem has a one-to-one relationship with LocalItem and FootItem.When adding data into the database , you need to pay attention to that if the foreign key is nullable or exists and the order in which data is added to the primary table and child table .
Here is a working demo ,you could refer to :
Model definition
public class BasicItem
{
public int BasicItemID { get; set; }
public string Name { get; set; }
public int FoodItemID { get; set; }
[ForeignKey("FoodItemID")]
public FoodItem FoodItem { get; set; }
public int LocalItemID { get; set; }
[ForeignKey("LocalItemID")]
public LocalItem LocalItem { get; set; }
}
public class FoodItem
{
public int FoodItemID { get; set; }
public string Name { get; set; }
//public int BasicItemID { get; set; }
public BasicItem BasicItem { get; set; }
}
public class LocalItem
{
public int LocalItemID { get; set; }
public string Name { get; set; }
//public int BasicItemID { get; set; }
public BasicItem BasicItem { get; set; }
}
public class ItemModel
{
public BasicItem BasicItem;
public FoodItem FoodItem;
public LocalItem LocalItem;
public ItemModel()
{
BasicItem = new BasicItem();
FoodItem = new FoodItem();
LocalItem = new LocalItem();
}
}
Controller
public async Task<IActionResult> ProductAdd(ItemModel ItemModel)
{
if (ItemModel.BasicItem != null)
{
if (ItemModel.LocalItem != null)
{
await db.LocalItems.AddAsync(ItemModel.LocalItem);
await db.FoodItems.AddAsync(ItemModel.FoodItem);
}
//same for FoodItem
ItemModel.BasicItem.LocalItem = ItemModel.LocalItem;
ItemModel.BasicItem.FoodItem = ItemModel.FoodItem;
await db.BasicItems.AddAsync(ItemModel.BasicItem);
await db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(ItemModel);
}
Okay, we can divide my situation into 2 basic cases:
Creating new entities
Updating entities
In first case it's pretty simple and easy cause you can create new object, fill it up, setup relations (you can only setup relation in one object like basicItem.FoodItem = foodItem, you don't need to do foodItem.BasicItem = basicItem, cause EF will automatically connect them) and send it to db, and it will work.
In second case, it's a little more complicated, cause in case to update data in db, you must get a related entity to a context. It's brings it's own limitations. And again you can have two approaches:
Create new object and manually (or through auto-mapper, but I didn't dig into this) overwrite fields of db related object at the end.
Fetch object from db at the beginning, pass it it through actions and change data on fly (if you want/need, you can even update db record on fly).
They are quite the same in a way, that you need to choose what field to update and write some code dbFoodItem.Weight = userInput.Weight.
So in my case I took second approach, and cause I collected data in multiple actions, I used session to data storage object between them.
I have a problem where I create an object containing a list, load it into my database, run a query that returns the object, but find the list null. All other properties of the object are as they should be. I'm using a list called "Ints" that is filled with a few integers but I've tried using other types.
Here's my model:
public class CourseModel
{
public int CourseModelId { get; set; }
public virtual ICollection<int> Ints { get; set; } // the variable in question
public string Name { get; set; }
public string Overview { get; set; }
}
And here's my database population (The database is called LearnYou):
public class LearnYouDbContextInitializer : DropCreateDatabaseAlways<LearnYouDbContext>
{
protected override void Seed(LearnYouDbContext context)
{
context.Courses.Add(new CourseModel()
{
Name = "C# Programming",
Overview = "You'll learn some C#",
Ints = new List<int> { 1, 42, 3 },
});
context.SaveChanges();
}
}
Here's the controller code for querying the object:
// GET: Course/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
CourseModel courseModel = db.Courses.Find(id);
// DEBUGGING THE PREVIOUS LINE SHOWS INTS IS NULL
if (courseModel == null)
{
return HttpNotFound();
}
return View(courseModel);
}
The "Ints" property is not null after saving the context in the database population part but is always null when it's queried (I visit the page ~Edit/1 to debug). I just can't figure out why when all other properties are fine. Any ideas? Thanks.
An ICollection in a model indicates a Parent->Child relationship. However, I doubt EF will be able to determine how to create a child table for an ICollection of integers. Here is what I would do.
Create a new model Ints (or whatever it actually represents):
public class Ints {
public int Value { get; set;}
}
Modify your original model to use it:
public class CourseModel
{
public int CourseModelId { get; set; }
public virtual ICollection<Ints> Ints { get; set; } // See the difference?
public string Name { get; set; }
public string Overview { get; set; }
}
That should make it work.
It Is not working because you are mapping directly to a int primitive type of .net and Entity Framework doesn't allow it.
In this case what you can do is create your onw object for example and sql table like
public class Ints {
{
public Course Course { get; set; }
public int IntValue { ger; set ; }
}
And referencing it from CourseModel
public virtual List<Ints> Ints { get; set; }
I have a pair of ViewModels that references data from a number of tables. One for displaying and one for editing.
When I return data from the display ViewModel I can map all the relevant fields using ValueInjecter InjectFrom functionality.
What do I do next to get the database to update?
If I send the models to my Update method in the repository I can see the changes in the model but the context doesn't pick them up. Am I missing a step or is there a better way of doing this?
If I try to modify one table at a time I can get the context to pick up the changes but then get an error as follows:
Store update, insert, or delete statement affected an unexpected
number of rows (0).
---EDIT---
I've updated the code and moved the mapping into the repository but I'm still getting the same error even though the debugger shows the entities with the new values.
ViewModels
public partial class HouseholdEditViewModel //for displaying in browser
{
public int entityID { get; set; }
public int familyID { get; set; }
public string UPRN { get; set; }
public string address { get; set; }
public HousingTypeDropDownViewModel housingTypeID { get; set; }
public KeyworkerDropDownViewModel keyworkerID { get; set; }
public string startDate { get; set; }
public bool loneParent { get; set; }
public string familyPhoneCode { get; set; }
public string familyPhone { get; set; }
}
public partial class HouseholdAddViewModel //for mapping to database
{
public int familyID { get; set; }
public string UPRN { get; set; }
public string address { get; set; }
public int entityTypeID { get; set; }
public int housingTypeID { get; set; }
public int keyworkerID { get; set; }
public DateTime startDate { get; set; }
public bool loneParent { get; set; }
public string familyPhoneCode { get; set; }
public string familyPhone { get; set; }
}
Repository (Current version - I've attempted a few different things without success)
public interface IHouseholdRepository : IDisposable
{
//other methods here...
void Update(HouseholdAddViewModel model, int id);
}
public void Update(HouseholdAddViewModel model, int id)
{
//check address exists
var address = (from u in context.tAddress
where model.UPRN.Contains(u.UPRN)
select u.UPRN);
var ae = new tAddressEntity();
ae.InjectFrom(model);
ae.entityID = id;
ae.UPRN = model.UPRN;
context.tAddressEntity.Attach(ae);
context.Entry(ae).State = EntityState.Modified;
var e = new tEntity();
e.InjectFrom(model);
e.entityID = id;
e.entityName = model.address;
e.tAddressEntity.Add(ae);
context.tEntity.Attach(e);
context.Entry(e).State = EntityState.Modified;
var a = new tAddress();
a.InjectFrom(model);
context.tAddress.Attach(a);
context.Entry(a).State = address.ToString() == string.Empty ?
EntityState.Added :
EntityState.Modified;
var hs = new tHousingStatus();
hs.InjectFrom(model);
hs.entityID = id;
context.tHousingStatus.Attach(hs);
context.Entry(hs).State = EntityState.Modified;
var k = new tKeyWorker();
k.InjectFrom(model);
k.entityID = id;
context.tKeyWorker.Attach(k);
context.Entry(k).State = EntityState.Modified;
var l = new tLoneParent();
l.InjectFrom(model);
l.entityID = id;
context.tLoneParent.Attach(l);
context.Entry(l).State = EntityState.Modified;
var h = new tHousehold();
h.InjectFrom(model);
h.entityID = id;
h.tHousingStatus.Add(hs);
h.tKeyWorker.Add(k);
h.tLoneParent.Add(l);
context.Entry(h).State = EntityState.Modified;
context.SaveChanges();
}
Controller
[HttpPost]
public ActionResult Edit(HouseholdAddViewModel model, int id)
{
model.entityTypeID = _repo.GetEntityType();
if (ModelState.IsValid)
{
_repo.Update(model, id);
return RedirectToAction("Index");
}
return View("Edit", id);
}
The easiest way to update an entity using EF is to retrieve the entity (using
it's key) and then apply the updates to that object instance. EF will automatically detect the updates to the entity and apply them when you call SaveChanges().
It seems as if you're creating new entities and you're not adding them to context so they
aren't being picked up.
I would change your Edit controller to do this
[HttpPost]
public ActionResult Edit(HouseholdAddViewModel model, int id)
{
model.entityTypeID = _repo.GetEntityType();
if (ModelState.IsValid)
{
var h = _repo.GetHousehold(id);
h.InjectFrom(model);
h.entityID = id;
//...
}
}