ef
Author(作者)实体模型类(一端) 注:一个作者可以写多本书,一本书只能有一个作者,所以作者是一端,书是多端
public class Author
{
public int Id { get; set; }
//作者姓名
public string AuthorName { get; set; }
}
Book(书)实体模型类(多端)
public class Book
{
public int Id { get; set; }
//书名
public string BookName { get; set; }
//作者姓名(一本书有一个位作者)
public int AuthorId { get; set; }
//导航属性,一本书有一个作者
public Author Author { get; set; }
}
上下文容器类MyDbcontext
using Microsoft.EntityFrameworkCore;
namespace MvcAPP.controllers
{
public class MyDbContext : DbContext
{
public DbSet<Book> Book { get; set; }
public DbSet<Author> Author { get; set; }
protected override void OnConfiguring(DbContextOptionsbuilder optionsBuilder)
{
//使用sql server数据库
//optionsBuilder.UseSqlServer("Data Source=192.168.0.207,1433;Initial Catalog=db_csdn_wx;User ID=hkuser;Password=csdn2018")
//使用mysql 数据库
optionsBuilder.UseMySql("Data Source=192.168.10.27;port=3306;Initial Catalog=Fbtest;user id=root;password=csdn2018;Character Set=utf8");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//配置表模型信息
var book = modelBuilder.Entity<Book>();
book.ToTable("Book").HasKey(r=>r.Id);
book.Property(r => r.BookName).HasMaxLength(20);
book.Property(r => r.AuthorId).Isrequired();
//配置关系
//一本书,有一个作者,外键是AuthorId,不许为空
book.HasOne(r => r.Author).WithMany().Hasforeignkey(r => r.AuthorId).IsRequired();
var author = modelBuilder.Entity<Author>();
author.ToTable("Author").HasKey(r => r.Id);
author.Property(r => r.AuthorName).IsRequired().HasMaxLength(20);
}
}
}
控制器
public class HomeController : Controller
{
public IActionResult Index()
{
using (MyDbContext db = new MyDbContext())
{
//var author = db.Author.Add(new Author() { AuthorName = "凡凡" });
//var book = db.Book.Add(new Book() { BookName = "CSDN日志指南", AuthorId = 1 });
//var isOk = db.SaveChanges();
var data1 = db.Book.Include(r => r.Author).Where(r=>r.AuthorId==1).ToList();
var data2 = db.Book.Include(r => r.Author).Where(r=>r.Author.AuthorName=="凡凡").ToList();
};
return View();
}
}
相关阅读
----------------------------------------数据库建模多表一对多和多对一、一对一、多对多------------------------------------
三张表 一对多 分页查询 <resultMap id="queryListMap" type="com.mtqg.identify.identifyServer.domain.Order">