EFCore- Save Entity with child entity records - entity-framework

Here are my models:
public partial class UserDTO
{
public int UserId { get; set; }
public ICollection<Userskills> Userskills { get; set; }
}
public partial class SkillsmasterDTO
{
public sbyte SkillId { get; set; }
public string Skill { get; set; }
public ICollection<Userskills> Userskills { get; set; }
}
public partial class UserskillsDTO
{
public int UserId { get; set; }
public sbyte SkillId { get; set; }
public SkillsmasterDTO Skill { get; set; }
public UsermasterDTO User { get; set; }
}
public class UserMaster
{
public int UserId { get; set; }
public List<UserSkills> UserSkills{get;set;}
//other fields
}
public class SkillsMaster
{
public sbyte SkillId { get; set; }
public string Skill { get; set; }
}
public class UserSkills
{
public int UserId { get; set; }
public sbyte SkillId { get; set; }
public string Skill { get; set; }
}
I want to save UserMaster, and along with that I want to save UserSkills also.
I am sending data in following format:
{"FirstName": "Priya",
"LastName": "Dave",
"Email":"priya.dave#xyz.com",
"Password":"123456",
"ContactNo":"1234",
"RoleId":1,
"CreatedBy":15,
"UserTypeId":2,
"LocationId":1,
"BandId":1,
"PostId":1,
"IsActive":1,
"UserSkills":[{"SkillId":1}]
}
Code I've written for save is:
var insertedEmployee= unitOfWork.UserRepository.Add(Mapper.Map<Usermaster>(employee));
_unitOfWork.Save();
It is saving user details but UserSkills is not getting saved. How can I do that? I went through some blogs but not able to find proper solution.

Because UserSkills is persisted in a different table than UserMaster, you need to do the following for a unit of work.
Add UserMaster to context.UserMasters table
Add UserSkills to context.UserSkills table
Add UserSkills to context.UserMaster object
Then context.SaveChanges()

Related

Assp.net Core exeption ('Invalid column name 'ClassRoomClassId')

I have a problem with ASP.NET Core scaffolding. I just applied scaffolding on a simple relational model and I got this SqlException.
Microsoft.Data.SqlClient.SqlException: 'Invalid column name 'ClassRoomClassId'.'
All I have two models
ClassRoom
public class ClassRoom
{
[Key]
public int ClassId { get; set; }
public string ClassName { get; set; }
public virtual ICollection<Student> Student { get; set; }
}
Student
public class Student
{
[Key]
public int StuId { get; set; }
public string StuName { get; set; }
[ForeignKey("ClassId")]
public int? ClassId { get; set; }
public ClassRoom ClassRoom { get; set; }
}
And I get the exception when executing Students/Index.
// GET: Students
public IActionResult Index()
{
return View(_context.Student.ToList());
}
I have no column with this name 'ClassRoomClassId' !!
what would be the problem?
Try changing [ForeignKey("ClassId")] to [ForeignKey("ClassRoom")] or placing it on ClassRoom property:
public class Student
{
...
public int? ClassId { get; set; }
[ForeignKey("ClassId")]
public ClassRoom ClassRoom { get; set; }
}

Returning Entity with its children

Hi I am trying to return all vehicles with their recorded mileage through an api using ASP.Net Core with the following code:
// GET: api/values
[HttpGet]
public IEnumerable<Vehicle> Get()
{
return _context.Vehicles.Include(m=>m.Mileages).ToList();
}
However this only returns the first vehicle with its mileages and not the others (there are five dummy vehicles in the db all with an initial mileage).
If I change the code to:
// GET: api/values
[HttpGet]
public IEnumerable<Vehicle> Get()
{
return _context.Vehicles.ToList();
}
it returns the full list of vehicles but no mileage.
My class files are:
public class Vehicle
{
public Vehicle()
{
Mileages = new List<Mileage>();
}
public int Id { get; set; }
public string Registration { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public Marked Marked { get; set; }
public ICollection<Mileage> Mileages { get; set; }
}
and
public class Mileage
{
public int Id { get; set; }
public DateTime MileageDate { get; set; }
public string RecordedMileage { get; set; }
//Navigation Properties
public int VehicleId { get; set; }
public Vehicle Vehicle { get; set; }
}
thanks for looking!
Tuppers
you can have them auto-load (lazy loading) using proxies... but for that, your foreign entities and collections must be marked virtual in your POCOs:
public class Mileage
{
public int Id { get; set; }
public DateTime MileageDate { get; set; }
public string RecordedMileage { get; set; }
//Navigation Properties
public int VehicleId { get; set; }
public virtual Vehicle Vehicle { get; set; }
}
public class Vehicle
{
public Vehicle()
{
Mileages = new List<Mileage>();
}
public int Id { get; set; }
public string Registration { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public Marked Marked { get; set; }
public virtual ICollection<Mileage> Mileages { get; set; }
}
The proxy creation and lazy loading turned on, but that's the default in EF6.
https://msdn.microsoft.com/en-us/data/jj574232.aspx
Let me know if this works.
Well after a lot of searching I managed to find a solution. I used the following:
[HttpGet]
public IEnumerable<VehicleDto> Get()
{
var query = _context.Vehicles.Select(v => new VehicleDto
{
Registration = v.Registration,
Make = v.Make,
Model = v.Model,
Marked = v.Marked,
Mileages = v.Mileages.Select(m => new MileageDto
{
MileageDate = m.MileageDate,
RecordedMileage = m.RecordedMileage
})
.ToList(),
})
.ToList();
return (IEnumerable<VehicleDto>) query.AsEnumerable();
this doesn't seem to be the most elegant way of doing this, if anyone could offer any advice but it does return what is required.
The DTO's look like:
public class VehicleDto
{
public string Registration { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public Marked Marked { get; set; }
public ICollection<MileageDto> Mileages { get; set; }
}
and
public class MileageDto
{
public DateTime MileageDate { get; set; }
public string RecordedMileage { get; set; }
}
Thanks for taking the time to look at this
Tuppers

EF 6 Code First Mapping one-to-many

Can someone please help me with mapping the following hierarchy with EF 6 code first? I can find anything useful for the below example in the documentation.
namespace Contacts {
public class Person
{
public Person()
{
this.Emails = new HashSet<Email>();
}
public long Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Email> Emails { get; set; }
}
public class Company
{
public Company()
{
this.Emails = new HashSet<Email>();
}
public long Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Email> Emails { get; set; }
}
public class Email
{
public string Value { get; set; }
public string Label { get; set; }
public string TargetId { get; set; }
public string TargetType { get; set; }
}
}
TargetType can be set to Company or Person depending on the entity that contains the Email instance.
DB Schema:

Have a list of objects as a foreign key

If I have two classes:
public class Event
{
public int EventId { get; set; }
public string EventName { get; set; }
}
and
public class Dog
{
public int DogId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
I would like for my event-class to be able to have a list of dog attached to it.
How can I make my event-class understand that I want it to be able to contain a list of dogs?
I am using entity framework. Thank you!
Assuming you're using Code-First:
public class Event
{
public int EventId { get; set; }
public string EventName { get; set; }
public virtual ICollection<Dog> Dogs { get; set; }
}
public class Dog
{
public int DogId { get; set; }
[ForeignKey("Event")]
public int EventID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public virtual Event Event { get; set; }
}

Entity Framework 4.3 CF many - to - many relationship saving object?

When creating many to many relationship using EF 4.3 code first approach, I cannot save data to connecting table, also cannot any examples on how to fill this table using saving object to Icollection... Here is my example:
MODELS
public class Hospital
{
//PK
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string County { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public Guid User_Id { get; set; }
//FK
public virtual ICollection<Operator> Operators { get; set; }
}
public class Operator
{
//PK
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Dob { get; set; }
public string Email { get; set; }
//FK
public virtual ICollection<Hospital> Hospitals { get; set; }
}
public class Project: DbContext
{
public DbSet<Hospital> Hospitals { get; set; }
public DbSet<Operator> Operators { get; set; }
}
CONTROLLER
public void AddOperater()
{
Hospital h = new Hospital();
h = db.Hospitals.Single(a=>a.Id ==1);
var o = new Operator();
o.FirstName = "John";
o.LastName = "Doe";
o.Dob = new DateTime(1988,2,12);
o.Email = "johndoe#gmail.com";
o.Hospitals.Add(h);
db.SaveChanges();
}
With this approach I keep getting error here: o.Hospitals.Add(h); even when my Hospital instance is filled with data. How exactly to save data to both tables, the dbo.Operators and dbo.OperatorHospital which is relationship table?
o.Hospitals.Add(h) will fail because the list is a null list. You cannot call Add() on a null list. Typically most people get around this by instantiating the list in the constructor of the entity... like so... the current line is blowing up due to a CSharp issue.
public class Hospital
{
//PK
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string County { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public Guid User_Id { get; set; }
//FK
public virtual ICollection<Operator> Operators { get; set; }
public Hospital()
{
Operators = new List<Operator>();
}
}
public class Operator
{
//PK
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Dob { get; set; }
public string Email { get; set; }
//FK
public virtual ICollection<Hospital> Hospitals { get; set; }
public Operator()
{
Hospitals = new List<Hospital>();
}
}