【问题标题】:Create a Foreign Key Using "Code First" but actually have the DB First使用“代码优先”创建外键,但实际上首先使用数据库
【发布时间】:2016-02-19 02:14:10
【问题描述】:

我的 Sql Server 数据库中有这些视图:

Shipment.Shipment
     * ShipmentId --> PK
     * CourierId

Ref.Courier
     * CourierId --> PK

由于这些是视图,因此它们上没有外键。基础表是旧表,也没有外键。

但我想让我的实体框架模型认为有外键。 (具体Shipment.Shipment.CourierId => Ref.Courier.CourierId

我可以先在数据库中执行此操作,但我最近切换到“代码优先”,我似乎无法使用 ForeignKey 属性使其工作。

但是,我并没有真正做到“代码优先”。我从现有数据库中的视图改造了我的实体类。

那么,使用“代码优先”语法,我如何向现有实体添加关联/外键?(即使数据库中没有)

这是我现有实体的配对版本:

[Table("Shipment.Shipment")]
public partial class Shipment
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ShipmentId { get; set; }

    public int CourierId { get; set; }

    [StringLength(50)]
    public string Airbill { get; set; }
}


[Table("Ref.Courier")]
public partial class Courier
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int CourierId { get; set; }

    [StringLength(50)]
    public string CourierName { get; set; }
}

【问题讨论】:

  • 尝试添加公共虚拟Courier Courier { get;放; } 在 shipping 类和公共虚拟 Shipment Shipment { get;放; } 在快递类
  • @AnshulNigam 做到了!很简单! (虽然我只需要为我的场景添加到货件类)。如果您想发布作为答案,我会接受。 (谢谢!)

标签: .net entity-framework ef-code-first entity-framework-6


【解决方案1】:

把你的代码改成

[Table("Shipment.Shipment")]
public partial class Shipment
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ShipmentId { get; set; }

    public int CourierId { get; set; }

    /* this will tell EF about relationship with Courier,assuming it is 1-1 */
    public virtual Courier Courier { get; set; }

    [StringLength(50)]
    public string Airbill { get; set; }
}


[Table("Ref.Courier")]
public partial class Courier
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int CourierId { get; set; }

    [StringLength(50)]
    public string CourierName { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-12
    • 2013-10-11
    • 2014-09-11
    相关资源
    最近更新 更多