Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Code First: Many-to-Many + Additional Property

I have the following tables: Country, Language and Country2Language

Country2Language is the linking table that creates the M:M relationship which is defined using Fluent Mapping:

mb.Entity<Country>()                             
  .HasMany(e => e.Languages)
  .WithMany(set => set.Countries)                
  .Map(mc =>
         {
           mc.ToTable("Country2Language");
           mc.MapLeftKey("CountryShortName");
           mc.MapRightKey("LanguagesID");                            
         }
      );  

My question: How can I add an additional DateTime "DateCreated" property?

like image 260
Mike Avatar asked Dec 06 '25 05:12

Mike


2 Answers

Would it work to create the table with the created column and then set the default value in the database to the GetTime function (or w/e it is)? Then just use the left/right mapping and let the db automatically handle the default value for created?

I've had issues in the past where EF wants to insert null into columns if you don't specify the column is a db generated value, but the fact this is for a many-to-many relationship it probably wouldn't even know it was there and should always let it become the default.

like image 82
Chris Marisic Avatar answered Dec 08 '25 17:12

Chris Marisic


You have to create an entity for your mapping that maps to the table.

public class Country2Language {
    [Key] 
    [Column(Order = 0)] 
    [ForeignKey("CountryShortName")] 
    public int CountryShortname{ get; set; } 

    [Key] 
    [Column(Order = 1)] 
    [ForeignKey("LanguagesID")] 
    public int LanguagesID { get; set; } 

    public DateTime DateCreated {get; set;}
}
like image 23
Erik Funkenbusch Avatar answered Dec 08 '25 17:12

Erik Funkenbusch