C# EntityFramework .NETCore 2.0 Many-to-Many - c#

.. Hello I know there's been already plenty of questions on this, but still can't get it right no matter what.
I need a many-to-many with custom join table, but every time I try to fetch collection it's still empty.
First class:
public class Test1 {
[Key]
public int id { get; set; }
public virtual ICollection<TestToTest> others { get; set; }
public Test1() {
others = new HashSet<TestToTest>();
}
}
Second one:
public class Test2 {
[Key]
public int id { get; set; }
public virtual ICollection<TestToTest> others { get; set; }
public Test2() {
others = new HashSet<TestToTest>();
}
}
And the join table:
public class TestToTest {
[Key]
public int id { get; set; }
[ForeignKey("Test1")]
public int test1Id { get; set; }
[ForeignKey("Test2")]
public int test2Id { get; set; }
public virtual Test1 test1 { get; set; }
public virtual Test2 test2 { get; set; }
}
But still when I try to get one of them with query like:
var cont = new MyContext(); //DbContext
Test1 t1 = cont.test1.Find(1); // Fetches first class ok
var tt = t1.others; // Empty array
I really have no idea what more I'm missing there in other to make it work.
If I add a new one to context then it's ok... as long as it's cached -> and it does write row into db. But after restart (without any cache in context), field 'others' is always empty.
Thanks for any help in advance.

It's not loading as child relationship are setup for Eager Loading. Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query, so that we don't need to execute a separate query for related entities. Eager loading is achieved using the Include() method. So if the relationship entity is not loaded using include then it would NOT be loaded.
Change the code as
Test1 t1 = cont.test1.Include(t => t.others).SingleOrDefault(t => t.id == 1);
You can read about Eager Loading at this Microsoft document.

Related

Error Object Id' is unknown when attempting to save changes. Adding Many to Many to the DB

I have objects with many to many relationship.
public class Executor
{
public long Id { get; set; }
public string Name { get; set; }
public List<Competency> Competency { get; set; }
}
public class Competency
{
public long Id { get; set; }
public string CompetencyName { get; set; }
public List<Executor> Executor { get; set; }
}
I am using EF Core 5 and PostgreSQL DB. I can`t just add new Executor to DB, first I need to find all competencies in the DB because of this problem.
So, my code now is like this:
public async Task<ServiceResponse<ExecutorDto>> AddExecutor(ExecutorDto newExecutor, long userId)
{
var serviceResponse = new ServiceResponse<ExecutorDto>();
try
{
var executor = _mapper.Map<Executor>(newExecutor);
executor.Competency.Clear();
executor.Competency = _context.Competencies.Where(i => newExecutor.Competency.Contains(i)).ToList();
_context.Executors.Add(executor);
await _context.SaveChangesAsync();
...
But on the Save moment I have error.
The value of 'CompetencyExecutor (Dictionary<string, object>).CompetencyId' is unknown when attempting to save changes. This is because the property is also part of a foreign key for which the principal entity in the relationship is not known.
I was trying to resolve this in many ways, but I can`t find the solution.
Well, it was stupid, the problem was because one of the Competency in the List has Id=0. PostreSQL recognises 0 as NULL. Just need to change Id to 1 or another positive number.

.Net Core Entity Framework .Include Eager load does not load entity

My first question - be kind :-).
In the code below, I am attempting to reference an "Include(d)" entity (Schedules) to obtain its Name property. In EF 6, both "schedule" and "schedule_2" return the correct value of Name. In EF Core, "schedule" returns NULL and "schedule_2" returns the correct value of Name.
I do not understand why I should have to load the "schedules" List. Shouldn't the .Include force an Eager Load of the Schedules for each Election such that each Election Schedule's Name property would be available for the "schedule" assignment?
// Relevant Model entities in database
// DbSet<Election> Elections { get; set; }
//
// The following are the related classes defined in the database context...
public class Election
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Schedule> Schedules { get; set; }
}
public class Schedule
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public int? CfsElectionId { get; set; }
public string Name { get; set; }
[Required] // sets cascade delete
[ForeignKey("CFSElectionID")]
public virtual Election Election { get; set; }
}
class Program
{
static void Main()
{
var db = new FfmsDbContext();
var elections = db.Elections
.Include(i => i.Schedules)
.ToList();
//The following returns NULL?
var schedule = elections.First().Schedules?.First().Name ?? "NULL";
var schedules = db.Schedules
.ToList();
//The following returns the correct Name property?
var schedule_2 = elections.First().Schedules?.First().Name ?? "NULL";
Console.WriteLine($#"sched: {schedule}");
Console.WriteLine($#"schedules.First().Name: {schedules.First().Name}");
Console.WriteLine($#"sched2: {schedule_2}");
Console.WriteLine("Done...");
Console.ReadLine();
}
}
/*
Output...
sched: NULL
schedules.First().Name: Candidates
sched2: Candidates
Done...
*/
Turns out that my problem ended up being in the References of the Class.
I had accidentally chosen System.Data.Entity as the offered choice for .Include.
The correct reference should have been Microsoft.EntityFrameworkCore.
Once I adjusted the reference, the .Include worked as desired.

Entity framework relationships

I have these three entities:
public class Dog
{
public int DogId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public bool Checked { get; set; }
public string DogImage { get; set; }
public virtual ICollection<Result> Results { get; set; }
}
public class Event
{
public int EventId { get; set; }
public string EventName { get; set; }
public string EventLocation { get; set; }
public string EventType { get; set; }
public string EventDate { get; set; }
public virtual ICollection<Result> Results { get; set; }
}
public class Result
{
public int ResultId { get; set; }
public int Track { get; set; }
public int Obedience { get; set; }
public int Protection { get; set; }
[ForeignKey("Dog")]
public int DogId { get; set; }
public virtual Dog Dog { get; set; }
[ForeignKey("Event")]
public int EventId { get; set; }
public virtual Event Event { get; set; }
}
I´ve been getting help from here before in order to set it up like this.
Entity Framework errors when trying to create many-to-many relationship
So the way it is now I guess the result is the "glue" that ties these classes together containing foreign keys to the two other tables.
What I have been trying to achieve for days now is to:
Create an event.
Add dogs to the event.
Add results to the dogs participating in the choosenEvent.
Lets say I create an event like this:
[HttpPost]
public ActionResult CreateEvent(Event newEvent)
{
newEvent.EventDate = newEvent.EventDate.ToString();
_ef.AddEvent(newEvent);
return View();
}
Now I guess the next step would be to add a list of dogs to this event and in order to do that I need to somehow use my result-class since that's the "glue"-class. Please let me know if I'm even on the right track here.
It is not really a good idea to do many to many relationships like how you've done. See here
In order to get a proper many to many relationship, mapped in the proper way in the database, that doesn't have pitfalls, I would try it this way:
public class Dog {}
public class Event {}
public class Result {}
// This is a linking table between Dog and Results
public class DogResult
{
public int Id {get;set;}
public int DogId {get;set;}
public int ResultId {get;set;}
}
// This is a linking table between Events and Results
public class EventResult
{
public int Id {get;set;}
public int EventId {get;set;}
public int ResultId {get;set;}
}
When you now write your query you can do this:
using (var context = new DbContext())
{
var dogs = context.Dogs();
var dogResults = context.DogResults();
var results = context.Results();
var dogsAndResults = dogs.Join(
dogResults,
d => d.Id,
r => r.DogId,
(dog, dogResult) => new { dog, dogResult })
.Join(
results,
a => a.dogResult.ResultId,
r => r.Id,
(anon, result) => new { anon.dog, result });
}
It is a bit nasty looking, but it will give you back a list of anonymous objects containing a Dog and its related Result. But obviously it would be better to do this in a stored proc:
using (var context = new DbContext())
{
var results = context.Database.ExecuteStoreQuery<SomeResultDto>("SELECT * .... JOIN ... ");
}
This is cleaner, because you are using SQL.
This is a more complex way of dealing with it. But far more performant, especially if you understand fully how entity framework executes LINQ.
Obviously if you want to create these links:
using (var context = new DbContext())
{
context.Dogs.AddRange(dogs); // dogs being a list of dog entities
context.Results.AddRange(results); // events being a list of results entities
context.DogResults.AddRange(dogResults); // a list of the links
}
It is completely up to you how you create these links. To turn this into a sproc as well, you want to create some custom User Defined Table Types and use them as a Table Value Parameter.
var dogResults = dogs.SelectMany( d => results.Select ( r => new DogResult { DogId = d.Id, ResultId = r.Id } ) );
That is a beast of a LINQ query and basically it gets every dog and links it to every result. Run it in LinqPad and Dump the values.
I've only done this using the fluent method (when I was learning I found you can do everything in fluent, but not with annotations, so I've not looked into them), the following creates a many to many between my Unit entity and my UnitService entity:
modelBuilder.Entity<Unit>()
.HasMany<UnitService>(u => u.Services)
.WithMany(us => us.Units);
This code is in the protected override void OnModelCreating(DbModelBuilder modelBuilder) method.
In your case Event is Unit and Dog is UnitService.
Oh ooops, you don't need that at all, your 'join' table is your results table, in my case I don't care about the join table so its all hidden.
Maybe something like:
modelBuilder.Entity<Result>()
.HasMany<Event>(e => e.Results);
modelBuilder.Entity<Result>()
.HasMany<Dog>(d => d.Results);

Why does my ASP.NET MVC 4 application create new entities instead of updating the old ones?

EDIT: The solution I selected probably wasn't the best, but it definitely worked. I'll be going through my code over the next week (once this project is done) and I'll update my question when I understand what went wrong.
I'm using the ASP.NET MVC 4 framework with Entity 5. Here's some code:
The class to be instantiated and saved (fresh) in the database:
public class ClassCancellation
{
[Key]
public int Id { get; set; }
public Faculty Professor { get; set; }
public DateTime CancelledOn { get; set; }
public Course Course { get; set; }
[Required]
public ClassDate ClassCancelled { get; set; }
public Message CancellationMessage { get; set; }
[Required]
public List<Student> Students { get; set; }
}
It's mapped from the viewmodel called CancellationFull (with AutoMapper):
public class CancellationForList
{
[Key]
public int Id { get; set; }
public CourseForList Course { get; set; }
public ClassDateForList ClassCancelled { get; set; }
}
public class CancellationFull : CancellationForList
{
public CancellationFull()
{
this.Students = new List<StudentForList>();
}
public FacultyForList Professor { get; set; }
public MessageForList CancellationMessage { get; set; }
public DateTime CancelledOn { get; set; }
public List<StudentForList> Students { get; set; }
}
This is the repo method that turns a CancellationFull into a ClassCancellation and then saves it to the database:
public CancellationFull createClassCancellation(CancellationFull c)
{
ClassCancellation newCancellation = Mapper.Map<ClassCancellation>(c);
dc.ClassCancellations.Add(newCancellation);
dc.SaveChanges();
return Mapper.Map<CancellationFull>(dc.ClassCancellations.FirstOrDefault(cc => cc.Id == newCancellation.Id));
}
Why, for the love of god why, does the database create new objects for Faculty and Course when the Id (primary key) of each's existing entity counterpart is provided? It might also be doing the same with Student objects but I haven't looked that closely.
Before the ClassCancellation instance is saved to the database the debugger shows that it's attributes Professor of type Faculty and Course of type Course have the correct primary key - that is, the primary key of the already existing entities of those types that I'm trying to update with a reference to the new ClassCancellation object.
Driving me nuts. Feel free to ask for clarification!
EDIT:
Here's the logic where the CancellationFull viewmodel is constructed from form data and viewmodels about existing objects retrieved from their respective repos:
newCancellation = new CancellationFull();
newCancellation.CancelledOn = DateTime.Now;
newCancellation.ClassCancelled = repoClass.getClassDateForListById(Int32.Parse(classIds[i]));
newCancellation.Course = repoCourse.getForList(newCancellation.ClassCancelled.Course.Id);
newCancellation.CancellationMessage = repoMessage.getMessageForList(newMessage.Id);
newCancellation.Professor = repoFac.getFacultyForList((int)Session["facId"]);
var students = repoStudent.getStudentsForListByCourse(newCancellation.Course.Id);
foreach ( var student in students )
{
newCancellation.Students.Add(student);
}
repoCancellation.createClassCancellation(newCancellation);
Here's an example of one of those repo methods (the rest are very similar):
public CourseForList getForList(int? id)
{
return Mapper.Map<CourseForList>(dc.Courses.FirstOrDefault(c => c.Id == id));
}
What I find the easiest solution is when updating a model, clear any related entities, then re add them.
ie:
newCancellation.Students.Clear();
foreach ( var student in students )
{
newCancellation.Students.Add(student);
}
Try using Attach() instead of Add()
dc.ClassCancellations.Attach(newCancellation);
dc.SaveChanges();
Add() is used for new objects that do not already exist in the database. Attach() is used for creating relationships to entities that already exist in the database.
EDIT
Without seeing your code, the best solution I can recommend to attach is to create a 'stub' instance and then attach that to your newCancellation:
var existingCourse = new Course{ Id = newCancellation.ClassCancelled.Course.Id };
db.Courses.Attach(existingCourse);
newCancellation.Course = existingCourse;
The problem is that you have multiple contexts, or units of work. When you add the newCancellation to the dc context, it also adds any related entity in the object graph that is not tracked in the dc context. I think your best option is:
dc.ClassCancellations.Add(newCancellation);
dc.Entry(newCancellation.Course).State = EntityState.Unchanged;
dc.Entry(newCancellation.Faculty).State = EntityState.Unchanged;
See Julie Lerman's article on this issue for an explanation and other options.
In my opinion, EF should recognize entities that have autonumbered keys and not insert them if the key is assigned.

How to handle projections in RavenDB

Given domain model...
public class Entity
{
public int Id { get; set; }
public Category Category { get; set; }
}
public class Category
{
public string Title { get; set; }
}
... I want to project results of a select query to this view model:
public class EntityViewModel
{
public int Id { get; set; }
public string CategoryTitle { get; set; }
}
I have tried the following query:
var viewModel = (from entity in _documentSession.Query<Entity>()
select new EntityViewModel
{
Id = entity.Id,
CategoryTitle = entity.Category.Title
}.ToList();
The result of this is only partially correct: the Id is set, the CategoryTitle is not. I understand this behaviour is by design, but I suspect there is an API to handle this scenario.
How should such a projection be handled in RavenDB?
Update: I am using build 1.0.573 in embedded mode.
Updated 2: I have forked RavenDB repository, added a failing test to demonstrate this behaviour and created a pull request (#444). Will post more info as I find out.
Looks like it is actually a bug. See pull request #444 for more information.
I will update this answer when this is fixed in a stable release.
Fixed in the current stable release.

Categories

Resources