模型配置可以通過(guò)Fluent API和注解的方式
-
FluentAPI步驟
- 新建Products 和Category類
新建Products類
Products
public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public int CategoryId { get; set; } public virtual Category Category { get; set; } public string Description { get; set; } public DateTime CreateTime { get; set; } public DateTime UpdateTime { get; set; } }
?
?
新建Category類
Category
public class Category { public int Id { get; set; } public string Name { get; set; } public ICollection<Product> Products { get; set; } }
- 新建Products 和Category類
- 他們之間存在一對(duì)多的關(guān)系
配置實(shí)體屬性
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
#region Product
modelBuilder.Entity<Product>().ToTable("Products", "dbo")
.Property(p => p.Name)
.HasColumnName("ProductName");//配置表名 列名
modelBuilder.Entity<Product>().HasKey(r => r.Id);//配置主鍵
modelBuilder.Entity<Product>()
.Property(r => r.Name).IsRequired()
.HasMaxLength(500);//配置長(zhǎng)度 和必填
modelBuilder.Entity<Product>()
.Property(r => r.CreateTime).HasDefaultValue(DateTime.Now);//配置默認(rèn)值
modelBuilder.Entity<Product>()
.Property(r => r.Price).HasColumnType("decimal(18,2)").IsRequired();
#endregion
#region Category
modelBuilder.Entity<Category>().ToTable("Categories", "dbo")
.Property(c => c.Name)
.HasColumnName("CategoryName");
modelBuilder.Entity<Category>().HasKey(r => r.Id);
modelBuilder.Entity<Product>()
.HasOne(p => p.Category)
.WithMany(c => c.Products)
.HasForeignKey(p => p.CategoryId);
#endregion
base.OnModelCreating(modelBuilder);
}
Fluent API??配置一對(duì)一的關(guān)系
一對(duì)一關(guān)系表示兩個(gè)實(shí)體存在唯一的關(guān)系,每個(gè)實(shí)體只能關(guān)聯(lián)到另一個(gè)實(shí)體
新建User和UserAddress類
User類
? public class User
{
public int Id { get; set; }
public string UserName { get; set; }
public UserAddress UserAddress { get; set; }
}
FluentAPI 中多對(duì)多關(guān)系
例如Student和Course之間存在多對(duì)多關(guān)系
Student
? public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Course> Courses { get; set; }
}
?
Course
? public class Course
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Student> Students { get; set; }
}
OnModelCreating中配置
? modelBuilder.Entity<Student>()
.HasMany(r => r.Courses)
.WithMany(r => r.Students)
.UsingEntity(r => r.ToTable("StudentCourse"));
#endregion
base.OnModelCreating(modelBuilder);
?文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-577481.html
注解形式
數(shù)據(jù)注解通過(guò)實(shí)體類的屬性添加特性來(lái)指定配置信息文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-577481.html
- [Key]指定主鍵屬性
- [Require]指定必填屬性(非空)
- [MaxLength(100)]最大為100的長(zhǎng)度,字符串屬性的最大長(zhǎng)度
- [ColumnName("ProductName")] 用于指定屬性列對(duì)應(yīng)的數(shù)據(jù)庫(kù)列名
- [Table("Products")]用于指定實(shí)體對(duì)應(yīng)數(shù)據(jù)庫(kù)的表名
- [ForeignKey("ColumnID")]:用于指定外鍵屬性
- ?
- ?
到了這里,關(guān)于netcore模型配置的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!