[英]How to map table without primary key Entity Framework
I'm using Entity Framework to map some tables, but I can't do this unless I declare some column as the primary key. 我正在使用Entity Framework映射一些表,但是除非声明某些列作为主键,否则我将无法做到这一点。
The problem here is that my table in my database don't have a primary key and has millions of rows. 这里的问题是数据库中的表没有主键,并且有数百万行。 I don't have permission to create a new
Id
column. 我无权创建新的
Id
列。
[Table("MYTABLE")]
public class myTable
{
[Column("NUMX")]
public virtual string NumX { get; set; }
[Column("NAME")]
public virtual string Name { get; set; }
[Column("AGE")]
public virtual int AGE { get; set; }
}
Obs: If I add the [Key]
attribute to some column like Age
, it works, but returns the wrong data. 观察:如果我将
[Key]
属性添加到诸如Age
类的某些列中,它将起作用,但是返回错误的数据。
Is there some way to omit the primary key? 有什么办法可以省略主键吗?
Entity Framework requires a primary key unlike SQL. 实体框架需要不同于SQL的主键。
EF use the primary key to uniquely identify rows (for example when you use .Find()
or to perform update operations). EF使用主键唯一地标识行(例如,当您使用
.Find()
或执行更新操作时)。
Infact not having a primary key remember a SQL VIEW, where you can only read data . 实际上,如果没有主键,请记住一个SQL VIEW,您只能在其中读取数据 。
If any of the columns uniquely identify a certain row set it as a primary key ( it can't be NULL ) also if in Sql it isn't a key. 如果任何列唯一地标识某行,则将其设置为主键( 不能为NULL ),如果在Sql中它不是键。 Otherwise if the combination of the columns are uniquely, create a composite key with these columns.
否则,如果列的组合是唯一的,则使用这些列创建一个组合键。
Remember that you should have a primary key in the 99% of cases, when you don't have a primary key you should stop and think if it make sense. 请记住,在99%的情况下,您应该有一个主键,当您没有主键时,应该停下来思考一下是否有意义。
I Figured out the problem. 我解决了这个问题。 Composite Keys works for me: eg: In my Context I defined some keys , not only one, but three keys:
复合键为我工作:例如:在上下文中,我定义了一些键 ,不仅是一个,而且是三个键:
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
**//Here is the secret**
modelBuilder.Entity<MyModel>().HasKey(x => new { x.NumX, x.Name,x.Age});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.