Nov 25, 2014
2 mins read
兩個類別之間,一個包含集合導覽屬性,一個包含引用屬性,就會被當成一對多關系
主表
namespace ConsoleApplication1.Models { using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema;[Table("Topic")] public class Topic { public int TopicId { get; set; } public string Title { get; set; } public virtual ICollection<Reply> Reply { get; set; } }
}
namespace ConsoleApplication1.Models { using System.ComponentModel.DataAnnotations.Schema;[Table("Reply")] public class Reply { public int ReplyId { get; set; } public int TopicId { get; set; } // public int TopicTopicId { get; set; } // public int TheTopicTopicId { get; set; } public string Title { get; set; } public virtual Topic TheTopic { get; set; } }
}
namespace ConsoleApplication1.Models { using System.ComponentModel.DataAnnotations.Schema;[Table("Reply")] public class Reply { public int ReplyId { get; set; } [ForeignKey("TheTopic")] public int tid { get; set; } public string Title { get; set; } public virtual Topic TheTopic { get; set; } }
}
namespace ConsoleApplication1.Models { using System.ComponentModel.DataAnnotations.Schema;[Table("Reply")] public class Reply { public int ReplyId { get; set; } public int tid { get; set; } public string Title { get; set; } [ForeignKey("tid")] public virtual Topic TheTopic { get; set; } }
}
namespace ConsoleApplication1.Models { using System.Data.Entity;public class DemoContext : DbContext { public DbSet<Topic> Topic { get; set; } public DbSet<Reply> Reply { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Topic>() .HasMany(x => x.Reply) .WithRequired(x => x.TheTopic) .HasForeignKey(x => x.tid) .WillCascadeOnDelete(true); } }
}
Sharing is caring!