How do I remove underscore of foreign key fields i

2019-01-08 10:51发布

I've got multiple classes (including TPT) in my project. Each POCO has a BaseClass, which has a GUID (called GlobalKey) as primary key.

First I used DataAnnotations to create correct foreign keys. But then I've got problems synchronizing the corresponding GUID with the object itself.

Now I want to have only one virtual navigation property so that the GUID field in the database is created by NamingConvention. But the field name always adds an underscore followed by the word GlobalKey (which is right). When I want to remove the underscore, I don't want to go thru all my POCOs in the fluent API to do this:

// Remove underscore from Navigation-Field     
modelBuilder.Entity<Person>()
            .HasOptional(x => x.Address)
            .WithMany()
            .Map(a => a.MapKey("AddressGlobalKey"));

Any ideas to do this for all POCOS by overwriting a convention?

Thanks in advance.

Andreas

7条回答
Anthone
2楼-- · 2019-01-08 11:19

You can do one of two things:

  1. Follow EF conventions in naming of foreign keys, i.e. if you have virtual Address, define your key property as AddressId

  2. Tell EF explicitly what to use. One way to do this is with Fluent API, as you are currently doing. You can also use data annotations, though:

    [ForeignKey("Address")]
    public int? AddressGlobalKey { get; set; }
    
    public virtual Address Address { get; set; }
    

That's your only choices.

查看更多
登录 后发表回答