1-0 or 1-1 relationships and 1: n relationships in EF, ef
First, give a 1-0 relationship.
The User table includes the User name and password.
public class User { public int ID { get; set; } public string UserName { get; set; } public string Passwd { get; set; } public virtual UserInfo UserInfo { get; set; } }
UserInfo table includes user information
public class UserInfo { public int ID { get; set; } public string Name { get; set; } public string Phone { get; set; } public virtual User User { get; set; } }
Public class Video {public int ID {get; set;} public string Title {get; set;} public virtual ICollection <VideoRecord> Records {get; set ;}}
The Record table includes video viewing records.
public class VideoRecord { public int ID { get; set; } public DateTime CrateAt { get; set; } public string IP { get; set; } public Video Video { get; set; } }
ModelBuilder. entity <User> (). toTable ("Users"); modelBuilder. entity <User> (). hasKey (u => u. ID); modelBuilder. entity <UserInfo> (). toTable ("UserInfos"); modelBuilder. entity <UserInfo> (). hasKey (I => I. ID); // set modelBuilder for the "or" relationship. entity <User> (). hasOptional (u => u. userInfo ). withRequired (I => I. user); modelBuilder. entity <Video> (). toTable ("Videos"); modelBuilder. entity <Video> (). hasKey (v => v. ID); modelBuilder. entity <VideoRecord> (). toTable ("VideoRecords"); modelBuilder. entity <VideoRecord> (). hasKey (r => r. ID); // set modelBuilder for the "1: n" relation. entity <Video> (). hasMany (v => v. records ). withRequired (r => r. video );
Test procedure
Context context = new Context (); UserInfo userInfo = new UserInfo () {ID = 1, Name = "Li zhanpeng", Phone = "3205 "}; user user = new User () {ID = 1, UserName = "lizhanpeng", Passwd = "123456", UserInfo = userInfo}; context. set <User> (). add (user); context. saveChanges (); context. set <User> (). include (x => x. userInfo ). toList (). forEach (x => {Console. writeLine (x. userName + "Real name:" + x. userInfo. name) ;}); List <VideoRecord> records = new List <VideoRecord> (); records. add (new VideoRecord () {ID = 1, IP = "127.0.0.1", CrateAt = DateTime. now}); records. add (new VideoRecord () {ID = 2, IP = "127.0.0.1", CrateAt = DateTime. now}); Video video = new Video () {ID = 1, Title = "Video 1", Records = records}; context. set <Video> (). add (video); context. saveChanges (); var vd = context. set <Video> (). include (x => x. records ). firstOrDefault (); vd. records. toList (). forEach (r => {Console. writeLine ("Viewer IP:" + r. IP + "Browse video" + vd. title) ;}); // reference http://www.cnblogs.com/dudu/archive/2011/07/09/entity_framework_one_to_many.html