使用自定义列名映射外键 [英] Mapping a foreign key with a custom column name

查看:458
本文介绍了使用自定义列名映射外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是使用Entity Framework 4.3的代码。我收到以下错误:


System.InvalidOperationException:类型WidgetDistributor.WidgetEntity上的属性WidgetSequence的ForeignKeyAttribute不是有效。在依赖类型WidgetDistributor.WidgetEntity上找不到外键名称WIDGETSEQUENCE_ID。名称值应为逗号分隔的外键属性名称列表。


我的实体是这样的:

  [表(WIDGETENTITIES)] 
public class WidgetEntity {

[Column(WIDGETENTITY_ID)]
public int Id {get;组; }

[ForeignKey(WIDGETSEQUENCE_ID)]
public WidgetSequence Sequence {get;组; }

//和其他正确映射的属性
}

[表(WIDGETSEQUENCES)]
public class WidgetSequence {

[Column(WIDGETSEQUENCE_ID)]
public int Id {get;组; }

[Column(NUMBER)]
public int Number {get;组; }
}

我的代码似乎正确。我在这里做了什么错?

解决方案

ForeignKey attibute expects a您的类中的属性名称作为参数,但是您指定了列名。使用流畅的映射。

  protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

modelBuilder .Entity< WidgetEntity>()
.HasRequired(w => w.Sequence)
.WithMany()
.Map(m => m.MapKey(WIDGETSEQUENCE_ID)) ;
}


I'm using Entity Framework 4.3 code-first with Oracle. I'm getting the following error:

System.InvalidOperationException : The ForeignKeyAttribute on property 'WidgetSequence' on type 'WidgetDistributor.WidgetEntity' is not valid. The foreign key name 'WIDGETSEQUENCE_ID' was not found on the dependent type 'WidgetDistributor.WidgetEntity'. The Name value should be a comma separated list of foreign key property names.

My entities are like this:

[Table("WIDGETENTITIES")]
public class WidgetEntity {

    [Column("WIDGETENTITY_ID")]
    public int Id { get; set; }

    [ForeignKey("WIDGETSEQUENCE_ID")]
    public WidgetSequence Sequence { get; set; }

    // and other properties that map correctly
}

[Table("WIDGETSEQUENCES")]
public class WidgetSequence { 

    [Column("WIDGETSEQUENCE_ID")]
    public int Id { get; set; }

    [Column("NUMBER")]
    public int Number { get; set; }
}

My code seems correct. What have I done wrong, here?

解决方案

ForeignKey attibute expects a property name in your class as the argument but you given the column name. Use fluent mappings.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

    modelBuilder.Entity<WidgetEntity>()
     .HasRequired(w => w.Sequence)
     .WithMany()
     .Map(m => m.MapKey("WIDGETSEQUENCE_ID"));
}

这篇关于使用自定义列名映射外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆