Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing default column name for navigation property

I have following class

public class TreeItem
{
    public long Id { get; set; }
    public Tree Tree { get; set; }
    public string Model { get; set; }
    public string Version { get; protected set; }
    public string Index { get; protected set; }
}

and I want to change default database's column name of property Tree. As default entity framework looking for "TreeId" column in databse, but our name's convention says that this column should be named as "tree_id"

If I try to set it as below:

 modelBuilder.Entity<TreeItem>().Property(t => t.Tree).HasColumnName("tree_id");

Ef throws me an exception with message:

Cannot call Property for the property 'Tree' on entity type 'TreeItem' because it is configured as a navigation property. Property can only be used to configure scalar properties.

Is it possible to change default column name of property Tree from "TreeId" to "tree_id"?

like image 927
bielu000 Avatar asked Sep 07 '17 08:09

bielu000


2 Answers

Try using MapKey():

modelBuilder.Entity<TreeItem>()
            .HasRequired(it => it.Tree)
            .WithMany()
            .Map(m => m.MapKey("tree_id"));

EDIT

For EF Core, you might have to use a work around as mentioned here:

modelBuilder.Entity<TreeItem>()
            .Property<long>("TreeId")
            .HasColumnName("tree_id");
like image 130
ashin Avatar answered Nov 15 '22 10:11

ashin


I always use a virtual objects when relating two entities to each other. When doing this you can also specify the column name for the FK as below:

public class TreeItem
{
    public long Id { get; set; }
    [Column("tree_id")]
    public int TreeId { get; set; }
    [ForeignKey("TreeId")]
    public virtual Tree Tree { get; set; }
    public string Model { get; set; }
    public string Version { get; protected set; }
    public string Index { get; protected set; }
}

public class Tree
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Generates this table in the database (I just created the Tree class as example for testing) If it's id is also a long make sure to change the datatype of the TreeId in the TreeItem class too.

enter image description here

like image 31
DenseCrab Avatar answered Nov 15 '22 12:11

DenseCrab