none
Entity Framework Mapping RRS feed

  • Question

  • Hi I am having issues with entity framework code first approach,

    I am having 50 tables in my database, all 50 tables have the same foreignkey reference from user table as a createdby, while generating that code-first user table it contains all 50 tables in this how to handle while retrieve data from user table, it showing invalid column name user_id in all tables. 

    Please anyone help me how to do this.

    Thanks in advance. 

    Friday, November 17, 2017 5:56 AM

All replies

  • Hi Prakash27,

    According to your description, you have 50 tables and all to tables have the same foreign key field named createby and want to map to the table named user, which have primary key field named user_id, if so, you could use fluent API (the code in Context file) to achieve it. like this:

     protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {    
                modelBuilder.Entity<User>()
                    .HasMany(e => e.Test1)
                    .WithRequired(e => e.User)
                    .HasForeignKey(e => e.createdby)
                    .WillCascadeOnDelete(false);
    
                modelBuilder.Entity<User>()
                    .HasMany(e => e.Test2)
                    .WithRequired(e => e.User)
                    .HasForeignKey(e => e.createdby)
                    .WillCascadeOnDelete(false);
    
    // other tables
            }

    For more information about entity Framework Fluent API - Relationships, please refer to

    https://msdn.microsoft.com/en-us/library/jj591620(v=vs.113).aspx

    Best regards,

    Zhanglong Wu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, November 17, 2017 7:37 AM
    Moderator
  • Fifty tables and using Code first. You are more braver and patient than I could ever be in making those objects.
    Sunday, November 19, 2017 12:51 PM