Reputation: 82297
When using Entity Framework 4.1, are there alternatives to the naming conventions for Navigation Properties?
For example instead of doing this:
public virtual MyObject MyObject { get; set; }
To be
public virtual MyObject SomeOtherName { get; set; }
UPDATE:
When the [ForeignKey("OldStepId")]
and [ForeignKey("NewStepId")]
attribute is added, the generated SQL then becomes:
{SELECT
`Extent1`.`CompletedId`,
`Extent1`.`OldStepId`,
`Extent1`.`NewStepId`,
`Extent1`.`Name`,
`Extent1`.`Step_StepId`,
`Extent1`.`Step_StepId1`
FROM `Completed` AS `Extent1`}
which, the last two columns do not exist.
Upvotes: 2
Views: 1949
Reputation: 67115
You can use the Data Annotations or the Fluent API to do this
Attribute Way
public virtual Int32 MyObjectId{get;set;}
[ForeignKey("MyObjectId")]
public virtual MyObject SomeOtherName { get; set; }
Fluent Way
modelBuilder.Entity<Type>()
.HasRequired(p => p.SomeOtherName)
.WithMany(d => d.Type)
.HasForeignKey(p => p.MyObjectId)
RESPONSE TO UPDATE
If you have a List in your MyOjbect class, then you need to mark that List as [InverseProperty("SomeOtherName")]
. This might be why you are getting extra columns in your SQL. This keeps two-way relationships from being doubled up by telling the generator where the main column really is.
Upvotes: 4
Reputation: 177163
You can name them as you like. You must distinguish between navigation properties which have a (scalar) foreign key property exposed in the class ("Foreign Key associations") and navigation properties which have not ("Independent Associations"):
Foreign Key associations:
[ForeignKey("VeryDifferentFKPropertyName")] // refers to property, NOT column
public virtual MyObject SomeOtherName { get; set; }
[Column("JustAnotherColumnName")] // map property to column name
public int VeryDifferentFKPropertyName { get; set; }
With Fluent API:
modelBuilder.Entity<SomeEntity>()
.HasRequired(e => e.SomeOtherName) // or .HasOptional(...)
.WithMany()
.HasForeignKey(e => e.VeryDifferentFKPropertyName);
modelBuilder.Entity<SomeEntity>()
.Property(e => e.VeryDifferentFKPropertyName)
.HasColumnName("JustAnotherColumnName");
Independent Associations:
public virtual MyObject SomeOtherName { get; set; }
You can map the foreign key column name only with Fluent API:
modelBuilder.Entity<SomeEntity>()
.HasRequired(e => e.SomeOtherName) // or .HasOptional(...)
.WithMany()
.Map(a => a.MapKey("JustAnotherColumnName"));
Upvotes: 0
Reputation: 50728
If you add a T4 template to generate the content, you can pretty much adjust the naming scheme to whatever you want...
Upvotes: 0
Reputation: 1227
I generally call them the same name as the Foreign Key for the Nav Props.
Upvotes: 1