Entity Framework Core Part 11 - Relationships

Sdílet
Vložit
  • čas přidán 3. 12. 2020
  • Coding Tutorial: Relational databases use have foreign keys. C# has collections. How can the two be reconciled? (Hint: Use EF Core).
    Source code available at: github.com/JasperKent/Entity-...
  • Věda a technologie

Komentáře • 46

  • @CodingTutorialsAreGo
    @CodingTutorialsAreGo  Před 3 lety +3

    Anything else you want to know about? Leave a comment.
    You can find the source code at github.com/JasperKent/Entity-Framework-Relationships
    For more on EF, subscribe at czcams.com/channels/qWQzlUDdllnLmtgfSgYTCA.html
    And give it a 👍 to show you liked it.

    • @finwwwfinwww4669
      @finwwwfinwww4669 Před 4 měsíci

      I was following the tutorial on my local... But EF core showed following error :
      Unable to determine the relationship represented by navigation property 'Course.Students' of type 'ICollection'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
      I am using EF 6 and .net 3.0..
      I was required to create A class StudenCources in Code..
      learn.microsoft.com/en-us/ef/core/modeling/relationships/many-to-many
      Am i missing something?
      Thanks

  • @scrup13s
    @scrup13s Před 3 lety +18

    I almost never react on a video. But i'm doing an internship for a company that requires this skillset and your tutorials are one of the best so far. much appreciated!

  • @gugomayora
    @gugomayora Před 2 lety +4

    AMAZING EXPLANATION... I WAS NOT UNDERSTANDING THE DIFFERENCE BETWEEN C# LOGIC AND DATABASE LOGIC TO CREATE RELATIONSHIPS... THIS VIDEO EXPLAIN IT REALLY WELL! THANK YOU!

  • @thuyuyenlovely8053
    @thuyuyenlovely8053 Před 2 lety +2

    the instructor explained very clearly .

  • @business3471
    @business3471 Před rokem +1

    I've been coming back to this video for the 4th time now. I really appreciate the content of this video. Thanks a lot!

  • @spwim
    @spwim Před 3 lety +5

    Thank you so much for these tutorials, i'm studying EF at the moment, so the series is right on time!

    • @spwim
      @spwim Před 3 lety +1

      oh, and yeah, too bad the sound is just as if you sit in an aquarium haha

    • @CodingTutorialsAreGo
      @CodingTutorialsAreGo  Před 3 lety

      Yeah - all sorted in later videos, I hope.

  • @HA-fq5xc
    @HA-fq5xc Před 2 lety +1

    Thank you so much from Saudi Arabia

  • @vadimemelin9068
    @vadimemelin9068 Před 2 lety +3

    Man, you helped me a lot!
    Thank you 🙏

  • @DamienSawyer
    @DamienSawyer Před rokem

    Thanks so much for putting that together. Really appreciated.

  • @ohaRega
    @ohaRega Před 2 lety +2

    Thanks! Helps me a lot.

  • @andresbeltran5779
    @andresbeltran5779 Před rokem +1

    Great video 🤠

  • @enndesigner
    @enndesigner Před měsícem +1

    perfect video! thank you so much!
    Could you give me a hint, how can one course have multiple editors?
    do i need to just replace in DbCOntext from .withOne() to .withMany()?

    • @CodingTutorialsAreGo
      @CodingTutorialsAreGo  Před 27 dny

      Do that, plus, change the Course class to have a collection of editors and in the Teacher class, remove the ForeignKey attribute from the CoursesEditted property.

  • @thrownewexceptionnonicknam3271

    6:30 - when I do that I get an error "The ALTER TABLE statement conflicted with the FOREIGN KEY constraint". Any ideas? I'd like to force a 1-* relationship.
    EDIT:
    I've removed all the data I had in the database and it solved the issue for me.

  • @renatoferreira9347
    @renatoferreira9347 Před 2 lety +5

    Great content! I still have a question though, what about duplicate many-to-many relationships. Let's say that a user can "Like" a post but also can put that post on the "favorite" list, both are many-to-many relationships between user and post how can I create two different tables with that relationship?

    • @CodingTutorialsAreGo
      @CodingTutorialsAreGo  Před 2 lety +3

      Great question! I think you'd have to do this using the Fluent API, something like:
      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
      base.OnModelCreating(modelBuilder);
      modelBuilder.Entity()
      .HasMany(u => u.Likes)
      .WithMany(p => p.Users)
      .Map(up=>
      {
      ac.MapLeftKey("User_Id");
      ac.MapRightKey("Post_Id");
      ac.ToTable("UserPostLikes");
      });
      modelBuilder.Entity()
      .HasMany(u => u.Favourties)
      .WithMany(p => p.Users)
      .Map(up=>
      {
      up.MapLeftKey("User_Id");
      up.MapRightKey("Post_Id");
      up.ToTable("UserPostFavourites");
      });
      }

    • @renatoferreira9347
      @renatoferreira9347 Před 2 lety

      @@CodingTutorialsAreGo Thank you so much for your suggestion I will definitely try it :D

  • @davidwhite2011
    @davidwhite2011 Před 3 lety +8

    I would give this a ten out of ten if you had a microphone that didn't make you sound like you were in a can. I can imagine that if someone was not a native English speaker the echo may make it impossible to understand. Keep up the good work and with this effort it would be worth spending less than $50 for a good mic.

    • @CodingTutorialsAreGo
      @CodingTutorialsAreGo  Před 3 lety +3

      Hi David. I noticed the sound problem on this. I have a Samson C01UPRO, which is usually fine, but for some reason it came out very poor on this recording.

    • @davidwhite2011
      @davidwhite2011 Před 3 lety +1

      @@CodingTutorialsAreGo Maybe selected the build in mic from the webcam?

    • @CodingTutorialsAreGo
      @CodingTutorialsAreGo  Před 3 lety +2

      @@davidwhite2011 Yeah, I'm thinking maybe something like that. I'll be checking everything more thoroughly in advance next time.

  • @bribit8021
    @bribit8021 Před 2 lety +2

    I visit your channel on CZcams regularly to see whats new. even check your Novel reading, that would be great if I know how to contact you

  • @bercodinglive
    @bercodinglive Před rokem +1

    Sorry sir, if I change the ICollection to List form everyting is gonna be same or should I add different things also ? Thank you from Turkey.

  • @alfonsdeda8912
    @alfonsdeda8912 Před 5 měsíci +1

    Hi, I have a one to one relationship, for example Person and Passport and I want to use the tpt hierarchy, but instead of using the personId in the Passport table I want to use the PassportId in Person table and the Passport table having only his data, could be done in ef core, I imagine that the Passport class won't be have any navigation property, any suggestion?

    • @CodingTutorialsAreGo
      @CodingTutorialsAreGo  Před 5 měsíci

      That's the default behaviour:
      public class Person
      {
      public int Id { get; set; }
      public required string Name { get; set; }
      public Passport? Passport { get; set; }
      }
      public class Passport
      {
      public int Id { get; set; }
      public int Number { get; set; }
      }
      Gives a PassportId on the Person table without any further configuration.

    • @alfonsdeda8912
      @alfonsdeda8912 Před 5 měsíci

      @@CodingTutorialsAreGo In this way I am using the tpt hierarchy and should be the slowest way, database side for me is the best option, the difference between others two types is so relevant from your experience?

  • @rodrigo6459
    @rodrigo6459 Před 2 lety +1

    Using Entity Framework Core 6.0.5
    Just in case someone else got this error "Introducing FOREIGN KEY constraint 'FK_Courses_Teachers_EditorId' on table 'Courses' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
    Could not create constraint or index. See previous errors."
    To solve it i had to change the code inside the OnModelCreating to:
    modelBuilder.Entity().HasOne(c => c.Editor).WithMany(t => t.CoursesEdited).OnDelete(DeleteBehavior.NoAction);
    modelBuilder.Entity().HasOne(c => c.Author).WithMany(t => t.CoursesWritten).OnDelete(DeleteBehavior.NoAction);

  • @KN-hv3gn
    @KN-hv3gn Před 2 lety

    Hi, I need some help. I followed your tutorial on creating a model extension for an entity. My Employee model has a property that is a many to many entity. For example Employee entity has many Departments so I have an EmployeeDepartment entity. In my Employee model extension I have a property for EmployeeDepartments. I do get the two EmployeeDepartment records but I don't get the EmployeeDepartment property for Department populated. The EmployeeDepartment.Department is null. When I don't use the model extension and just use the entity.Include.thenInclude, the Department is populated. What am I doing wrong?

    • @CodingTutorialsAreGo
      @CodingTutorialsAreGo  Před 2 lety

      You'll have to show me some code.

    • @KN-hv3gn
      @KN-hv3gn Před 2 lety

      @@CodingTutorialsAreGo I'm so happy you saw and responded. Is there a way I can send you the code and not post it here?

    • @CodingTutorialsAreGo
      @CodingTutorialsAreGo  Před 2 lety

      @@KN-hv3gnSorry, I can't really take on private consultancy.

  • @katrykonig2466
    @katrykonig2466 Před rokem +1

    How would you do if both Student and Classroom belong to two different assemblies ? How could you reference both sides? You fall in a Circular Dependencies !!

    • @CodingTutorialsAreGo
      @CodingTutorialsAreGo  Před rokem

      You're right! You can't have cyclic/reciprocal references across assembly boundaries. The usual fix would be introduce interfaces for both sides to be dependent on. See czcams.com/video/XydkF1AVbYE/video.html

    • @katrykonig2466
      @katrykonig2466 Před rokem

      @@CodingTutorialsAreGo Thanks for your replay, I have seen it. But there is also a problem, what will happen if the properties in the separated DLL changed, then the other DLL will not be notified and no error in the compile time, which means the probability of having errors in run-time/production will be high and hidden. That is also a serious problem.

    • @CodingTutorialsAreGo
      @CodingTutorialsAreGo  Před rokem

      @@katrykonig2466 Once an interface has been published, it should not be changed. However, even if it is changed, the client code will not use the new version until it's explicitly upgraded.

  • @jalanguevara1
    @jalanguevara1 Před 2 lety +1

    Hi,
    I have a Relationship like this:
    public class Config
    {
    [Key]
    public int ConfigId { get; set; }
    [ForeignKey("temperature_unit_id")]
    public TemperatureUnit temperature { get; set; }
    public int temperature_unit_id { get; set; }
    }
    public class TemperatureUnit
    {
    [Key]
    public int TemperatureUnitId { get; set; }
    public string name { get; set; }
    public string code { get; set; }
    }
    I want to be able to update the temperature using the Navigational Property temperature like so:
    {
    id: 1,
    temperature:
    {
    id: 2
    }
    } // This would be my PUT payload
    So let's say that before the POST the temperature_unit_id was 1 and I want to update it with 2.
    When I try that though, it asks me for the name and code fields for the temperature. It sounds like it would update the temperature table as well?
    I don't want to update the temperature unit fields, I just want to update the reference from 1, to 2.
    How would you do this? Do I need to send temperature_unit_id: 2 instead of the temperature object?
    Thanks,

    • @CodingTutorialsAreGo
      @CodingTutorialsAreGo  Před 2 lety

      Not entirely sure what your asking her, but it looks like your code is attempting to change the TemperatureUnitId (the primary key) of an existing TemperatureUnit object, which you can't do since it is fixed at initialization.
      I think what you want to do is change the temperature_unit_id of the Config class, not the TemperatureUnitId of the TemperatureUnit class.

    • @jalanguevara1
      @jalanguevara1 Před 2 lety

      @@CodingTutorialsAreGo sorry I don’t explain more clearly. Correct, I don’t want to update the primary key, I just want to update the temperature_unit_id of the Config class. I am able to do it now by updating temperature_unit_id. I just it could work by sending a different navigational property.

  • @akremhammami5328
    @akremhammami5328 Před 2 lety +1

    I hade to add OnDelete(DeleteBehavior.Restrict); on the OnModelCreating
    so it become
    modelBuilder.Entity().HasOne(c => c.Edditer).WithMany(t => t.CoursesEddited).OnDelete(DeleteBehavior.Restrict);
    I added this because I had this error
    Introducing FOREIGN KEY constraint 'FK_Courses_Teachers_EditterId' on table 'Courses' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
    Could not create constraint or index. See previous errors.