Skip to content

Clarify that FK shadow properties are usually created by convention #1016

Closed

Description

@mattfrear

> They are most often used for foreign key properties

The Fluent API example on this page isn't much help. Can you provide an example that does something with relationships or foreign keys?


Document Details

⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Activity

  1. ajcvickers commented on Oct 2, 2018

    @ajcvickers
    Contributor
  2. mattfrear commented on Oct 2, 2018

    @mattfrear
    Author

    Yeah I know. My request still stands. There's a page about shadow properties, which says what they're most useful for, but then fails a decent example.

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Blog>()
                .Property<DateTime>("LastUpdated");
        }
    

    WTF does that line of code do? It's not obvious to me.

    99% of people won't bother to provide feedback when they struggle and will turn to google to find an answer. So when someone does provide feedback it shouldn't be disregarded.

  3. ajcvickers commented on Oct 2, 2018

    @ajcvickers
    Contributor

    @mattfrear Trying to connect the dots here, maybe the confusion is that they are commonly used for FKs, but rarely explicitly defined for FKs. Hence showing API here to define an FK in shadow state would not be terribly useful since that's not a very common thing to do. Would it be clearer to say, "They are most often used for foreign key properties, where they are added to the model by convention when no foreign key property has been found by convention or configured explicitly."

    With regard to not knowing what that line of code does, can you be more specific about what is ambiguous?

  4. mattfrear commented on Oct 2, 2018

    @mattfrear
    Author

    Would it be clearer to say, "They are most often used for foreign key properties, where they are added to the model by convention when no foreign key property has been found by convention or configured explicitly."

    Yes, I think that would be an improvement.

    With regard to not knowing what that line of code does, can you be more specific about what is ambiguous?

    I have re-read the page and now it makes sense, so please disregard my earlier comment.

    I landed on this page trying to solve a specific and frustrating problem (one to many relationship with a nullable int foreign key which should not be nullable), I was hoping this page would shed some light on my problem but I accept that I was perhaps looking in the wrong place. Sorry for being rude.

  5. ajcvickers commented on Oct 2, 2018

    @ajcvickers
    Contributor

    @mattfrear Np
    Re-opening because I think clarifying that FK shadow properties are usually created by convention would be useful.

  6. changed the title [-]Please provide a more useful example[/-] [+]Clarify that FK shadow properties are usually created by convention[/+] on Oct 2, 2018
  7. anth-git commented on Nov 2, 2018

    @anth-git

    I think that the example from https://docs.microsoft.com/en-us/ef/core/modeling/relationships#foreign-key should be used for the FluentApi paragraph.
    It seems to be quite valid usecase to have FK that doesn't follow convention but we want to configure it as a shadow property. So it would be much useful example than example of just creating some arbitrary "LastUpdated" property, that doesn't have any meaning, especially that you stated by yourself that shadow properties are are most often used for foreign key.

            // Add the shadow property to the model
            modelBuilder.Entity<Post>()
                .Property<int>("BlogForeignKey");
    
            // Use the shadow property as a foreign key
            modelBuilder.Entity<Post>()
                .HasOne(p => p.Blog)
                .WithMany(b => b.Posts)
                .HasForeignKey("BlogForeignKey");
    
  8. added this to the 2.2.0 milestone on Nov 10, 2018
  9. modified the milestones: 2.2.0, 3.0.0 on Feb 21, 2019
  10. Yuant-tobing commented on Mar 10, 2019

    @Yuant-tobing

    How to seed data to shadow properties ?

    Continent model

    public partial class Continent
    {
        public string Code { get; set; }
        public string Name { get; set; }
    
        public ICollection<Country> Countries { get; set; }
    }
    

    Country model

        public partial class Country
        {
            public Country() => Provinces = new HashSet<Province>();
    
            public int Code { get; set; }
            public string IsoA2 { get; set; }
            public string IsoA3 { get; set; }
            public string Name { get; set; }
            public string Capital { get; set; }
    
            public Continent Continent { get; set; }
            public ICollection<Province> Provinces { get; set; }
        }
    

    App context

                modelBuilder.Entity<Continent>(entity =>
                {
                    entity.HasKey(e => e.Code)
                        .HasName("PK_Continent");
    
                    entity.ToTable("continent");
    
                    entity.Property(e => e.Code)
                        .HasColumnName("code")
                        .HasMaxLength(2)
                        .IsUnicode(false)
                        .IsFixedLength()
                        .ValueGeneratedNever();
    
                    entity.Property(e => e.Name)
                        .IsRequired()
                        .HasColumnName("name")
                        .HasMaxLength(24)
                        .IsUnicode(false);
                });
    
                modelBuilder.Entity<Country>(entity =>
                {
                    entity.ToTable("country");
    
                    entity.HasKey(e => e.Code)
                        .HasName("PK_Country");
    
                    entity.Property(e => e.Code)
                        .HasColumnName("code")
                        .ValueGeneratedNever();
    
                    entity.Property(e => e.Capital)
                        .IsRequired(false)
                        .HasColumnName("capital")
                        .HasMaxLength(80)
                        .IsUnicode(false);
    
                    entity.Property(e => e.IsoA2)
                        .IsRequired()
                        .HasColumnName("iso_a2")
                        .HasMaxLength(2)
                        .IsUnicode(false)
                        .IsFixedLength();
    
                    entity.Property(e => e.IsoA3)
                        .IsRequired()
                        .HasColumnName("iso_a3")
                        .HasMaxLength(3)
                        .IsUnicode(false)
                        .IsFixedLength();
    
                    entity.Property(e => e.Name)
                        .HasColumnName("name")
                        .HasMaxLength(80)
                        .IsUnicode(false);
    
                    entity.Property<string>("continent_code")
                        .IsRequired()
                        .HasMaxLength(2)
                        .IsUnicode(false)
                        .IsFixedLength();
    
                    entity.HasIndex("continent_code");
    
                    entity.HasOne(d => d.Continent)
                        .WithMany(p => p.Countries)
                        .HasForeignKey("continent_code")
                        .HasConstraintName("FK_Country_Continent")
                        .OnDelete(DeleteBehavior.Cascade);
                });
    

    App data seeder

            public static void Initialize(NusaportContext context)
            {
                context.Database.EnsureCreated();
    
                if (!context.Continents.Any())
                {
                    var continents = new Continent[] {
                        new Continent { Code = "AF", Name = "Africa" },
                        .....
                    };
    
                    foreach (Continent c in continents)
                    {
                        context.Continents.Add(c);
                    }
    
                    context.SaveChanges();
                }
    
                if (!context.Countries.Any())
                {
                    var countries = new Country[] {
                        new Country { Code = 111, IsoA2 = "ZZ", IsoA3 = "ZZZ", Name = "Example", Capital = "Example" }
                    };
    
                    foreach (Country cn in countries)
                    {
                        context.Countries.Add(cn);
                    }
    
                return;
            }
    

    I need to insert continent_code's value while seeding data to database,

  11. ajcvickers commented on Mar 11, 2019

    @ajcvickers
    Contributor

    @Yuant-tobing Use an anonymous type as shown in the docs.

  12. 4 remaining items

  13. added this to the Backlog milestone on Aug 29, 2019
  14. pha3z commented on Oct 25, 2020

    @pha3z

    Can someone please explain this line of documentation?

    "We recommend explicitly adding the shadow property to the model before using it as a foreign key (as shown below)."

    It's on this page: https://docs.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key#shadow-foreign-key

    It's extremely frustrating, because I am trying to reduce volume of code. There's no explanation of what would happen if you call the .HasForeignKey(""BlogForeignKey") method without having explicitly defined the Shadow Property beforehand. How do I know whether or not I can omit the explicit property addition?

    UPDATE: After understanding the problem better, I opened a separate issue about this:
    #2807

  15. added a commit that references this issue on Nov 12, 2022
    3e16275
  16. added 2 commits that reference this issue on Nov 30, 2022
    a8e088f
    15fb84b
  17. modified the milestones: Backlog, 7.0.0 on Nov 30, 2022
  18. added a commit that references this issue on Feb 6, 2024
    3e14402
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions