C# 首先使用 EF 代码映射复合键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19792295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mapping composite keys using EF code first
提问by loyalflow
Sql server table:
Sql服务器表:
SomeId PK varchar(50) not null
OtherId PK int not null
How should I map this in EF 6 code first?
我应该如何首先在 EF 6 代码中映射它?
public class MyTable
{
[Key]
public string SomeId { get; set; }
[Key]
public int OtherId { get; set; }
}
I've seen some examples where you have to set the order for each column, is that required?
我看过一些例子,你必须为每一列设置顺序,这是必需的吗?
Is there official documentation on this somewhere?
某处是否有关于此的官方文档?
采纳答案by Corey Adler
You definitely need to put in the column order, otherwise how is SQL Server supposed to know which one goes first? Here's what you would need to do in your code:
你肯定需要把列顺序放进去,否则SQL Server怎么知道哪个先到呢?以下是您需要在代码中执行的操作:
public class MyTable
{
[Key, Column(Order = 0)]
public string SomeId { get; set; }
[Key, Column(Order = 1)]
public int OtherId { get; set; }
}
You can also look at this SO question. If you want official documentation, I would recommend looking at the official EF website. Hope this helps.
你也可以看看这个 SO question。如果您需要官方文档,我建议您查看EF 官方网站。希望这可以帮助。
EDIT: I just found a blog post from Julie Lerman with links to all kinds of EF 6 goodness. You can find whatever you need here.
编辑:我刚刚找到了 Julie Lerman 的一篇博客文章,其中包含指向各种 EF 6 优点的链接。你可以在这里找到你需要的任何东西。
回答by philn5d
Through Configuration, you can do this:
通过配置,您可以执行以下操作:
Model1
{
int fk_one,
int fk_two
}
Model2
{
int pk_one,
int pk_two,
}
then in the context config
然后在上下文配置中
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Model1>()
.HasRequired(e => e.Model2)
.WithMany(e => e.Model1s)
.HasForeignKey(e => new { e.fk_one, e.fk_two })
.WillCascadeOnDelete(false);
}
}
回答by Krishna
For Mapping Composite primary key using Entity framework we can use two approaches.
对于使用实体框架映射复合主键,我们可以使用两种方法。
1) By Overriding the OnModelCreating() Method
1)通过覆盖 OnModelCreating() 方法
For ex: I have the model class named VehicleFeature as shown below.
例如:我有一个名为 VehicleFeature 的模型类,如下所示。
public class VehicleFeature
{
public int VehicleId { get; set; }
public int FeatureId{get;set;}
public Vehicle Vehicle{get;set;}
public Feature Feature{get;set;}
}
The Code in my DBContext would be like ,
我的 DBContext 中的代码类似于,
public class VegaDbContext : DbContext
{
public DbSet<Make> Makes{get;set;}
public DbSet<Feature> Features{get;set;}
public VegaDbContext(DbContextOptions<VegaDbContext> options):base(options)
{
}
// we override the OnModelCreating method here.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<VehicleFeature>().HasKey(vf=> new {vf.VehicleId, vf.FeatureId});
}
}
2) By Data Annotations.
2)通过数据注释。
public class VehicleFeature
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int VehicleId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int FeatureId{get;set;}
public Vehicle Vehicle{get;set;}
public Feature Feature{get;set;}
}
Please refer the below links for the more information.
请参阅以下链接以获取更多信息。
1) https://msdn.microsoft.com/en-us/library/jj591617(v=vs.113).aspx
1) https://msdn.microsoft.com/en-us/library/jj591617(v=vs.113).aspx
回答by cmorgan091
I thought I would add to this question as it is the top google search result.
我想我会补充这个问题,因为它是谷歌搜索结果的顶部。
As has been noted in the comments, in EF Core there is no support for using annotations (Key attribute) and it must be done with fluent.
正如评论中所指出的,在 EF Core 中不支持使用注释(Key 属性),必须使用 fluent 完成。
As I was working on a large migration from EF6 to EF Core this was unsavoury and so I tried to hack it by using Reflection to look for the Key attribute and then apply it during OnModelCreating
由于我正在进行从 EF6 到 EF Core 的大规模迁移,这很令人讨厌,因此我尝试通过使用反射来查找 Key 属性然后在 OnModelCreating 期间应用它来破解它
// get all composite keys (entity decorated by more than 1 [Key] attribute
foreach (var entity in modelBuilder.Model.GetEntityTypes()
.Where(t =>
t.ClrType.GetProperties()
.Count(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(KeyAttribute))) > 1))
{
// get the keys in the appropriate order
var orderedKeys = entity.ClrType
.GetProperties()
.Where(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(KeyAttribute)))
.OrderBy(p =>
p.CustomAttributes.Single(x => x.AttributeType == typeof(ColumnAttribute))?
.NamedArguments?.Single(y => y.MemberName == nameof(ColumnAttribute.Order))
.TypedValue.Value ?? 0)
.Select(x => x.Name)
.ToArray();
// apply the keys to the model builder
modelBuilder.Entity(entity.ClrType).HasKey(orderedKeys);
}
I haven't fully tested this in all situations, but it works in my basic tests. Hope this helps someone
我还没有在所有情况下对此进行全面测试,但它适用于我的基本测试。希望这有助于某人