1

This applies to EF 5 and database first modeling. My model was built useing the EF generator from an existing DB.

I'm using the [Key] data annotation in my model classes because the primary key fields have names that are not in line with EF conventions.

Everything works, but when I open the root EDMX files, the model classes are updated and any manual changes I had made are lost.

Should I be making my changes in a different manner?

tintyethan
  • 1,772
  • 3
  • 20
  • 44

2 Answers2

1

You could update your T4 template to add in the data annotation for you on primary keys?

if (simpleProperties.Any())
{
    foreach (var edmProperty in simpleProperties)
    {
     if (ef.IsKey(edmProperty)){
#>
[Key]
<# } #>
Daniel Dawes
  • 975
  • 5
  • 16
  • I've never worked with the tt file before. I'm getting a "does not exist in the current context" error on simpleProperties and can't find any documentation online. Any instruction I'm missing? – tintyethan Sep 06 '13 at 19:17
  • @EthanPelton - Check around line 66 in the tt file, you should see the foreach already there with the variable simpleProperties – Daniel Dawes Sep 09 '13 at 11:53
  • That solved my issue. I wonder why it's not there by default? – almaz Oct 21 '13 at 17:38
  • this does not work in database first, as any changes made manually will be overwritten. – tintyethan Nov 14 '13 at 17:52
  • @EthanPelton Incorrect, changing the T4 template will permanently change the generation of the classes. – Daniel Dawes Nov 15 '13 at 09:45
  • Maybe there's a difference in our configuration. It sounds like you'r e familiar with some specific documentation that states this. In my environment, any change I make to the edmx is removed when I update from database, which makes sense in database first. – tintyethan Nov 15 '13 at 13:21
  • @EthanPelton That is correct, but the T4 template change as above would not be overwritten, the T4 template uses the EDMX to generate the classes, but adding things like the above is independent of a particular class, it is a global change to generate an attribute of [Key] if the field name in question is actually a primary key. – Daniel Dawes Nov 15 '13 at 14:59
0

the solution that worked for me was to overide the EF convention in OnModelCreating method in the context class.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<abk_Bookings>()
                    .HasKey(e => e.booking_number);}
tintyethan
  • 1,772
  • 3
  • 20
  • 44