将 2 个表绑定在一起(一对多关系)
我对 C#、EF Code First 等还很陌生,所以我的问题可能很简单。
我正在尝试创建一个非常简单的登录。每个用户必须有一个类型(管理员或客户端)。如何将用户类型绑定到用户表,而无需每次在数据库中插入新用户时生成新类型? 这是我的第一类代码:
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public bool Active { get; set; }
public UserType TypeId { get; set; }
}
public class UserType
{
public int Id { get; set; }
public string Type { get; set; }
}
public enum TypeEnum
{
Admin,
Client
}
当我启动应用程序时,我希望能够创建 2 个表:
- Users 是空的
- UserTypes 必须包含 2 种类型(管理员和客户端)。
然后,每次注册新用户时,每次将用户添加到 Users 表时,我都希望能够使用 UserTypes 表。
I am pretty new to c#, EF Code First and all that, so my question might be an easy one.
I am trying to create a very simple login. Each user must have a type (admin or client). How can I bind the usertype to my user table without generating a new type each time I insert a new user in the DB?
Here are my code first class:
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public bool Active { get; set; }
public UserType TypeId { get; set; }
}
public class UserType
{
public int Id { get; set; }
public string Type { get; set; }
}
public enum TypeEnum
{
Admin,
Client
}
When I launch the app, I want to be able to create 2 tables:
- Users which is empty
- UserTypes which must contain 2 types (Admin and Client).
Then, everytime I register a new user, so everytime I add a user to the Users table, I want to be able to use the UserTypes table.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不确定我是否理解正确,但您可以使用 EF Code-First 将初始数据播种到数据库中。如何执行此操作的示例如下:
实体框架插入初始数据重建时
如果您确实想在每次启动应用程序时重新创建表,您可以使用
DropCreateDatabaseAlways
初始化程序如示例中所述。为此,您将加载要从数据库分配的现有
UserType
,以便将其附加到上下文,然后创建新用户:附加到上下文 - 通过从数据库加载或调用显式
附加
- 确保UserType
不重复,即不会将UserType
的INSERT命令发送到数据库。Not sure if I understand this correctly but you can seed initial data into the database with EF Code-First. An example how to do that is here:
Entity Framework Inserting Initial Data On Rebuild
If you really want to recreate the tables with every launch of your application you can use the
DropCreateDatabaseAlways<T>
initializer as mentioned in the example.For this you would load the existing
UserType
you want to assign from the database so that it is attached to the context and then create the new user:Attaching to the context - by either loading from the database or calling
Attach
explicitely - makes sure that theUserType
is not duplicated, i.e. no INSERT command will be sent to the database for theUserType
.使用新版本的 EF(目前超出官方 4.1 版本:实体框架 2011 年 6 月 CTP)您也可以这样做:
数据将作为整数保存在数据库中,但在应用程序中您可以使用枚举 像这样:
With new version of EF (currently beyond the offical 4.1 version: Entity Framework June 2011 CTP) you can also do that:
The data will be saved as integer in your database but within your application you can use your enum like this: