FreeSql (十八)導航屬性

導航屬性是 FreeSql 的特點功能之一,可經過約定配置、或自定義配置對象間的關係。html

導航屬性有 OneToMany, ManyToOne, ManyToMany, OneToOne, Parent 五種配置關係。git

有了導航屬性,多表查詢會很是方便,lambda 表達式中直接使用導航對象點點點,舒服!!github

除了查詢還有更多其餘的特性在後續文章中再介紹。sql

自定義導航關係

//導航屬性,OneToMany
[Navigate("song_id")]
public virtual List<song_tag> Obj_song_tag { get; set; }

//導航屬性,ManyToOne/OneToOne
[Navigate("song_id")]
public virtual Song Obj_song { get; set; }

//導航屬性,ManyToMany
[Navigate(ManyToMany = typeof(tag_song))]
public virtual List<tag> tags { get; set; }
  • 可約定,可不約定;
  • 不約定的,需指定 Navigate 特性關聯;
  • 無關聯的,查詢時能夠指明 On 條件,LeftJoin(a => a.Parent.Id == a.ParentId);
  • 已關聯的,直接使用導航對象就行,On 條件會自動附上;

也能夠使用 FluentApi 在外部設置導航關係:ui

fsql.CodeFirst.ConfigEntity<實體類>(a => a
    .Navigate(b => b.roles, null, typeof(多對多中間實體類))
    .Navigate(b => b.users, "uid")
);

優先級,特性 > FluentApicode

約定配置

OneToOne 一對一

class User {
    public int Id { get; set; } //Id、UserId、User_id

    public UserExt UserExt { get; set; }
}

class UserExt {
    public int id { get; set; } //Id、UserId、User_id、UserExtId、UserExt_id

    public User User { get; set; }
}

《OneToOne 一對一,怎麼添加數據?》htm

ManyToOne 多對一

class Group {
    public int Id { get; set; } //Id、GroupId、Group_id
}

class User {
    public int Id { get; set; } //Id、UserId、User_id


    public int AGroupId { get; set; }
    public Group AGroup { get; set; }

    public int BGroupId { get; set; }
    public Group BGroup { get; set; }
}

OneToMany 一對多

class Group {
    public int Id { get; set; } //Id、GroupId、Group_id

    public ICollection<User> AUsers { get; set; }
    public ICollection<User> BUsers { get; set; }
}

class User {
    public int Id { get; set; } //Id、UserId、User_id


    public int AGroupId { get; set; }
    public Group AGroup { get; set; }

    public int BGroupId { get; set; }
    public Group BGroup { get; set; }
}

《OneToMany 一對多,怎麼添加數據?》對象

Parent 父子

class Group {
    public int Id { get; set; } //Id、GroupId、Group_id

    public int ParentId { get; set; } //ParentId、Parent_id
    public Group Parent { get; set; }

    public ICollection<Group> Childs { get; set; }
}

父子關係,與一對多其實差很少,添加數據參數上面的鏈接;blog

ManyToMany 多對多

class Song {
    [Column(IsIdentity = true)]
    public int Id { get; set; }
    public string Title { get; set; }

    public virtual ICollection<Tag> Tags { get; set; }
}
class Song_tag {
    public int Song_id { get; set; }
    public virtual Song Song { get; set; }

    public int Tag_id { get; set; }
    public virtual Tag Tag { get; set; }
}
class Tag {
    [Column(IsIdentity = true)]
    public int Id { get; set; }
    public string Name { get; set; }

    public int? Parent_id { get; set; }
    public virtual Tag Parent { get; set; }

    public virtual ICollection<Song> Songs { get; set; }
    public virtual ICollection<Tag> Tags { get; set; }
}

Song、Tag、Song_tag,這三個實體使用了 OneToMany、ManyToOne、Parent、ManyToMany 4種關係。事務

系列文章導航

相關文章
相關標籤/搜索