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; }
Related
I have a class :
public class Participant
{
[Key]
public int ParticipantId { get; set; }
[Column(TypeName ="nvarchar(50)")]
public string Email { get; set; }
[Column(TypeName = "nvarchar(50)")]
public string Name { get; set; }
public int Score { get; set; }
public int Timetaken { get; set; }
}
My endpoint:
public IActionResult GetAll()
{
var parts = _context.Participants.ToList();
if(!parts.Any())
return NotFound();
var participant = new ParticipantDto(parts);
return Ok(participant);
}
My Participant Dto:
public class ParticipantDto
{
private readonly Participant _participants;
public ParticipantDto(Participant participants)
{
_participants = participants;
}
}
I am trying the approach of passing the Participant object in the constructor and then assigning the Participant properties to DTO. I am aware how to do it for one Participant :
public string EmailAddress = _participants.Email;
etc
However, what If I want to return a List, how do I need to update my Dto to handle that?
For this statement,
var participant = new ParticipantDto(parts);
it is incorrect as you are passing the List<Participant> instance to the ParticipantDto constructor which the constructor is expected for the parameter value with the Participant type. You will get the compiler error for the unmatching type.
Hence, you need to iterate the list to transform each Participant element to the ParticipantDto type. You can use .Select() from System.Linq to do the iteration and transformation.
public IActionResult GetAll()
{
var parts = _context.Participants.ToList();
if(!parts.Any())
return NotFound();
List<ParticipantDto> participants = parts
.Select(x => new ParticipantDto(participant))
.Tolist();
return Ok(participants);
}
While in ParticipantDto, you need to perform the value mapping between the properties.
public class ParticipantDto
{
public ParticipantDto(Participant participant)
{
Email = participant.Email;
Name = participant.Name;
// Following assigning value from the properties of Participant to properties of ParticipantDto
}
public string Email { get; set; }
public string Name { get; set; }
// Following properties
}
Bonus:
You may look for AutoMapper which is a popular library for mapping between classes. (Wouldn't cover too much as the answer aims to focus and fix your current problem)
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 2 base classes which 1 for search criteria and other 1 for search results.
I also have 2 derived classes for User object versions of both of those.
When I put a breakpoint in the controller action I can see all properties are populated as I've hardcoded.
When I call this action directly in the browser, each of my derived object properties is null.
I'm guessing the JSON serialization is not able to tell the difference from the base class to the derived one.
Is there a way to solve this?
public class BaseSearchCriteria
{
public int Page { get; set; }
public int RecordsPerPage { get; set; }
}
public class BaseSearchResults
{
public int TotalResults { get; set; }
public virtual BaseSearchCriteria SearchCriteria { get; set; }
}
public class UserSearchCriteria : BaseSearchCriteria
{
public string Username { get; set; }
}
public class UserSearchResults : BaseSearchResults
{
public new UserSearchCriteria SearchCriteria { get; set; }
}
public JsonResult Search(UserSearchCriteria model)
{
var viewModel = new UserSearchResults
{
SearchCriteria = new UserSearchCriteria
{
Page = 1,
RecordsPerPage = 15
}
};
viewModel.TotalResults = 100;
return Json(viewModel, JsonRequestBehavior.AllowGet);
}
Maybe good way to deal with it is to use generics as Daniel A. White propose.
Sample gist here.
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);
Here is my data transfer object
public class LoadSourceDetail
{
public string LoadSourceCode { get; set; }
public string LoadSourceDesc { get; set; }
public IEnumerable<ReportingEntityDetail> ReportingEntity { get; set; }
}
public class ReportingEntityDetail
{
public string ReportingEntityCode { get; set; }
public string ReportingEntityDesc { get; set; }
}
And here is my ViewModel
public class LoadSourceViewModel
{
#region Construction
public LoadSourceViewModel ()
{
}
public LoadSourceViewModel(LoadSourceDetail data)
{
if (data != null)
{
LoadSourceCode = data.LoadSourceCode;
LoadSourceDesc = data.LoadSourceDesc;
ReportingEntity = // <-- ? not sure how to do this
};
}
#endregion
public string LoadSourceCode { get; set; }
public string LoadSourceDesc { get; set; }
public IEnumerable<ReportingEntityViewModel> ReportingEntity { get; set; }
}
public class ReportingEntityViewModel
{
public string ReportingEntityCode { get; set; }
public string ReportingEntityDesc { get; set; }
}
}
I'm not sure how to transfer the data from the LoadSourceDetail ReportingEntity to the LoadSourceViewModel ReportingEntity. I'm trying to transfer data from one IEnumerable to another IEnumerable.
I would use AutoMapper to do this:
https://github.com/AutoMapper/AutoMapper
http://automapper.org/
You can easily map collections, see https://github.com/AutoMapper/AutoMapper/wiki/Lists-and-arrays
It would look something like this:
var viewLoadSources = Mapper.Map<IEnumerable<LoadSourceDetail>, IEnumerable<LoadSourceViewModel>>(loadSources);
If you are using this in an MVC project I usually have an AutoMapper config in the App_Start that sets the configuration i.e. fields that do not match etc.
Without AutoMapper you will have to map each property one by one ,
Something like this :
LoadSourceDetail obj = FillLoadSourceDetail ();// fill from source or somewhere
// check for null before
ReportingEntity = obj.ReportingEntity
.Select(x => new ReportingEntityViewModel()
{
ReportingEntityCode = x.ReportingEntityCode,
ReportingEntityDesc x.ReportingEntityDesc
})
.ToList(); // here is 'x' is of type ReportingEntityDetail
You could point it to the same IEnumerable:
ReportingEntity = data.ReportingEntity;
If you want to make a deep copy, you could use ToList(), or ToArray():
ReportingEntity = data.ReportingEntity.ToList();
That will materialize the IEnumerable and store a snapshot in your view model.