entityFramework 一直没怎么用过,最近发现在开发阶段挺合适的,而且在某些场合也挺方便的(比如CMS系统自动生成数据的过程),于是研究下生成的表和实体类之间是怎么对应的。
0.NotMapped不映射到数据库,也不会存储到数据库
1.Required必须
[Required]
public string Name { set; get; }
2.,MaxLength,MinLength最大字符数和最小字符数
MaxLength(50),MinLength(1)
public string Name { set; get; }
3.[ForeignKey]外键
[Column("Parent")]
public int? Parent { set; get; }
[ForeignKey("Parent")]
public List<Role> Children { set; get; }
4.[Key]主键
[Key]
public int Id { set; get;}
5.可空
[Column("Parent")]
public int? Parent { set; get; }
6.[Table("User")]表名
[Table("User")]
public class User
{
[Key]
public int Id { set; get; }
[Required,MaxLength(30)]
public string Name { set; get; }
public List<Role> Roles { set; get; }
}
7.[Column]列名
[Column("Parent")]
public int? Parent { set; get; }
8.索引
Index(IsUnique=true)
9.默认值
构造函数自己初始化
10.多对多关系(用户-角色,用户有多个角色,角色同时属于多个用户)
[Table("User")]
public class User
{
[Key]
public int Id { set; get; }
[Required,MaxLength(30)]
public string Name { set; get; }
public List<Role> Roles { set; get; }
}
public class Role
{
[Key]
public int Id { set; get;}
[Required,MaxLength(50)]
public string Name { set; get; }
public List<User> User { set; get; }
[Column("Parent")]
public int? Parent { set; get; }
[ForeignKey("Parent")]
public List<Role> Children { set; get; }
}
public class MnContext : DbContext
{
public MnContext() : base("DbContext") {}
public DbSet<User> User { set; get; }
public DbSet<Role> Role { set; get; }
}
class Program
{
static void Main(string[] args)
{
using(var db = new MnContext())
{
if(!db.Database.Exists())
{
db.Database.Create();
}
User user = new User() { Name="UserName"};
Role role = new Role() { Name="超级管理员" };
Role rolec = new Role() { Name = "管理员" };
db.User.Add(user);
db.Role.Add(role);
db.Role.Add(rolec);
db.SaveChanges();
user.Roles = new List<Role>();
role.Children = new List<Role>();
user.Roles.Add(role);
user.Roles.Add(rolec);
role.Children.Add(rolec);
db.SaveChanges();
}
}
}
配置文件
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add name="DbContext" connectionString="data source=ASUS\SQLSERVER2012;initial catalog=Demo;persist security info=True;user id=sa;password=123456" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
结果还是比较满意的