Remove() with many-to-many relationship doesn't work - c#

Let's say I have two tables with a many-to-many relationship that generated with database first in edmx type:
public class Teacher
{
public int TeacherId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Cours> Courses { get; set; }
}
public class Course
{
public int CourseId { get; set; }
public string CourseName { get; set; }
public byte QtySession { get; set; }
public virtual ICollection<Teacher> Teachers { get; set; }
}
TeacherCourse
{
[key]
public int CourseId { get; set; }
[key]
public int TeacherId { get; set; }
}
//this is many to many relationship table But not generated with edmx
In following code I am trying to remove the one of row in TeacherCourse table. But the result is not correct(not any actions).
SabaEntities sabaEntities = new SabaEntities();
var teacher = sabaEntities.Teachers.FirstOrDefault(x => x.TeacherId == teacherId);
sabaEntities.Courses.FirstOrDefault(x => x.CourseId == courseId).Teachers.Remove(teacher);
sabaEntities.SaveChanges()
This code running without any error, but the result not corrected, because not remove row mentioned in TeacherCourse.
How can I solve it?

Related

How to define common property for two different entities in EF core?

I have two entities Student and course as below
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
[System.Text.Json.Serialization.JsonIgnore]
public virtual IList<Course> Courses { get; set; }
}
public class Course
{
public int Id { get; set; }
public string Name { get; set; }
public virtual IList<Student> Students { get; set; }
[ForeignKey(nameof(TeacherId))]
public int TeacherId {get;set;}
public Teacher Teacher { get; set; }
}
Now I want to add list of grades to two entities containing grade and id of the course or Student depending on the situation. Do I have to define a entity grade with studentId and CourseId or is there any other way to do it without creating entity
What you describe is a m:n-relationship between Course and Student with the extra information of the grade that was awarded for the participation. By creating the two navigation properties Student.Courses and Course.Students you have already created an implicit crosstab between the entities. In order to add the grade, I'd propose to create a dedicated entity, e.g. CourseParticipation that defines the relationship between Course and Student and also carries the extra information (up to now, the grade, later maybe more):
public class CourseParticipation
{
public int Id { get; set; }
public int CourseId { get; set; }
public Course Course { get; set; }
public int StudentId { get; set; }
public Student Student { get; set; }
public int Grade { get; set; }
}
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
[System.Text.Json.Serialization.JsonIgnore]
public virtual IList<CourseParticipation> Courses { get; set; }
}
public class Course
{
public int Id { get; set; }
public string Name { get; set; }
public virtual IList<CourseParticipation> Participants { get; set; }
[ForeignKey(nameof(TeacherId))]
public int TeacherId {get;set;}
public Teacher Teacher { get; set; }
}
This way, you make the relationship explicit and are prepared for later additions to the relationship.

Which one is the correct one-to-many relation in EF

i am designing a system and one of my entity has one to many relation as shown below.
public class Product
{
public int Id { get; set; }
}
public class CompetitorProduct
{
public int Id { get; set; }
public Product Product { get; set; }
}
competitorProduct indicates that product has a equivalent which is sold by different store. should i define one-to-many relation as shown above or below? which one is correct?
public class Product
{
public int Id { get; set; }
public virtual ICollection<CompetitorProduct> CompetitorProducts{ get; set; }
}
public class CompetitorProduct
{
public int Id { get; set; }
}
Assuming it is a one to many relationship (what would happen if a competitor product was competing with more than one of your products for example) you can do both and add in a foreign key as well.
public class Product
{
public int Id { get; set; }
public virtual ICollection<CompetitorProduct> CompetitorProducts { get; set; }
}
public class CompetitorProduct
{
public int Id { get; set; }
public int ProductId { get; set; }
public virtual Product Product { get; set; }
}
You can then set up your relationship using fluent API as so:
modelBuilder.Entity<CompetitorProduct>(entity =>
{
entity.HasOne(e => e.Product)
.WithMany(e => e.CompetitorProducts)
.HasForeignKey(e => e.ProductId)
.HasConstraintName("FK_ComptetitorProduct_Product");
});
This way you can access the competitor products from the product and the product from the competitor products.
Here is a quick example of a ecommerce site I have worked on and how we did table relations.
I removed a bunch of the fields so you can see what you really need. Once to make relations and run Add-Migration EF will handle the FK constraints for you as long as you identified them in models like how I have below.
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
Active = true;
CreateDateTimeUtc = DateTime.UtcNow;
ModifiedDateTimeUtc = DateTime.UtcNow;
}
[StringLength(500)]
public string FirstName { get; set; }
[StringLength(500)]
public string LastName { get; set; }
[StringLength(1000)]
public string Address { get; set; }
[StringLength(100)]
public string Unit { get; set; }
[StringLength(250)]
public string City { get; set; }
[StringLength(25)]
public string State { get; set; }
[StringLength(20)]
public string ZipCode { get; set; }
//This will give access to a list of child carts a user could have
[Index]
public bool Active { get; set; }
public virtual ICollection<Cart> Carts { get; set; }
// Account Profile Image
public byte[] ProfileImage { get; set; }
[StringLength(500)]
public string ProfileFilename { get; set; }
[StringLength(100)]
public string ProfileMimeType { get; set; }
}
[Table("Cart", Schema = "dbo")]
public class Cart : AbstractTable
{
public Cart()
{
IsComplete = false;
}
//This create relation to user table where I can get one unique user.
[StringLength(128)]
[ForeignKey("ApplicationUser")]
public string UserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
//These link us to child tables of Cart where we can get a LIST of the items below
public virtual ICollection<CartCategory> CartCategories { get; set; }
public virtual ICollection<CartItem> CartItems { get; set; }
// Marked when a payment/receipt is generated based off of this cart
public bool IsComplete { get; set; }
}
[Table("CartItem", Schema = "dbo")]
public class CartItem : AbstractTable
{
//This will return one unique cart id and let us access it as the parent record
[ForeignKey("Cart")]
public Guid CartId { get; set; }
public virtual Cart Cart { get; set; }
// Signifies if this was paid for in a receipt
public bool IsComplete { get; set; }
public virtual ICollection<CartItemCustomField> CustomFields { get; set; }
}

Including related entities with a many-to-many relationship between

I have a many-to-many relationship set up with Entity Framework like this:
public class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
public ICollection<StudentCourse> StudentCourses { get; set; }
}
public class Course
{
public int CourseId { get; set; }
public string Name { get; set; }
public ICollection<StudentCourse> StudentCourses { get; set; }
}
public class StudentCourse
{
public int StudentId { get; set; }
public Student Student { get; set; }
public int CourseId { get; set; }
public Course Course { get; set; }
}
This works great, I have Students and I have Courses, and StudentCourses is the many-to-many relationship between them.
I also have an Advisor class, which has a collection of StudentCourses that the Advisor is in charge of:
public class Advisor
{
public int AdvisorId { get; set; }
public ICollection<StudentCourse> StudentCourses { get; set; }
}
I would like to get a collection of Advisors and the StudentCourses they're in charge of, but also the data properties from the Student and Course objects (like Name), all at once. This works for me:
var advisors = await _dbContext.Advisors
.Include(a => a.StudentCourses)
.ThenInclude(sc => sc.Student)
Include(a => a.StudentCourses)
.ThenInclude(sc => sc.Course)
.ToListAsync();
But is this the only way I can do that? Seems wrong to have that duplicate Include statement

Many to Many Relationship with extra columns in EF 6 Code?

Say if I have the classic example of Student and Courses. A student can have many courses and course can have many students.
How do I make the middle table in EF 6 code if I wanted to add an extra field on the many table part?
Do I just make in code another class and then hook it up somehow?
DB Context
public class MyContext : DbContext
{
public MyContext (string nameOrConnectionString) : base(nameOrConnectionString)
{
// this.Configuration.ProxyCreationEnabled = false;
Database.SetInitializer(new CreateDatabaseIfNotExists<OSPContext>());
}
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<StudentCourse> StudentCourses { get; set; }
}
public class StudentCourse
{
[Key]
public Guid StudentCourseId { get; set; }
public Guid StudentId { get; set; }
[ForeignKey("StudentId")]
public virtual Student Student { get; set; } // Include this so you can access it later
public Guid CourseId { get; set; }
[ForeignKey("CourseId")]
public virtual Course Course { get; set; }
public int Permissions { get; set; }
}
public class Course
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Student> Students { get; set; } = new >();
}
public class Student
{
[Key]
public Guid Id { get; set; }
public string Email { get; set; }
public virtual ICollection<Course> Courses { get; set; } = new List<Course>();
}
Given you are code first I would do something like the following.
public class Student
{
[Key]
public int StudentId { get; set; }
public string Name { get; set; }
public List<StudentCourse> Courses { get; set; } // So you can access Courses for a student
}
public class Course
{
[Key]
public int CourseId { get; set; }
public string Name { get; set; }
public List<StudentCourse> Students { get; set; }
}
public class StudentCourse
{
[Key]
public int StudentCourseId { get; set; }
public int StudentId { get; set; }
[ForeignKey("StudentId")]
public Student Student { get; set; } // Include this so you can access it later
public int CourseId { get; set; }
[ForeignKey("CourseId")]
public Course Course { get; set; }
}
EDIT: Wanted to note relationships are established with Data Attributes, you could also use EF Fluent API to establish your relationships. The properties will look the same, but without the [ForeignKey("")]

Entity Framework Code First Relationships

I'm learning EF using Code First and I'm having a lot of trouble getting my relationships to build correctly.
A Simple Employee
public class Employee
{
[Key]
public int EmployeeId { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
}
A Simple Project
public class Project
{
[Key]
public int ProjectId { get; set; }
public String ProjectNumber { get; set; }
}
The time spent on the project
public class Time
{
[Key]
public int TimeId { get; set; }
public int EmployeeID { get; set; }
public String ProjectID { get; set; }
public long? TimeSpent { get; set; }
public virtual Employee Employee { get; set; }
public virtual Project Project { get; set; }
}
I'm trying to join Employee to Time on EmployeeID and join Project to Time on ProjectID and I just don't understand how EF determines relationships. I'm trying to use Data Annotations to define the relationships. I've tried using the ForeignKey annotation to define the relationships but that has not worked either.
What I have will run, but on the Project table, a new field named Project_ProjectID is created and if I try to run a query in VS I get an error saying that the column Time_TimeID is invalid (which it is). What am I doing wrong?
You shouldn't need DataAnnotations as conventions will work for you in this case
Try the following
public class Time
{
[Key]
public int TimeId { get; set; }
public int EmployeeID { get; set; }
public int ProjectID { get; set; } //<< Changed type from string
public long? TimeSpent { get; set; }
public virtual Employee Employee { get; set; }
public virtual Project Project { get; set; }
}
public class Employee
{
[Key]
public int EmployeeId { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
// Set up the other side of the relationship
public virtual ICollection<Time> Times { get; set; } // << Added
}
public class Project
{
[Key]
public int ProjectId { get; set; }
public String ProjectNumber { get; set; }
// Set up the other side of the relationship
public virtual ICollection<Time> Times { get; set; } // << Added
}
This article may help
http://msdn.microsoft.com/en-gb/data/jj679962.aspx

Categories