【问题标题】:EntityFramework and Model with fields of one class [closed]具有一类字段的实体框架和模型[关闭]
【发布时间】:2013-02-04 15:29:18
【问题描述】:

我有“用户”和“出价”模型。

当然还有 DateBase 中的“Users”和“Bids”表。 ("Bid" columns in postgres table)

我可以像这样映射一个“用户”字段:

    public int UserId { get; set; }
    public virtual User User { get; set; }

但不知道如何映射三个具有不同名称的“用户”字段。

    public int CreatorId { get; set; }//id of user in db table
    public int ManagerId { get; set; }//id of user in db table
    public int ExecutorId { get; set; }//id of user in db table
    public virtual User Creator { get; set; }
    public virtual User Manager { get; set; }
    public virtual User Executor { get; set; }

我该怎么办?

public class Bid
{
    public int BidId { get; set; }

    public string Title { get; set; }
    public string Text { get; set; }

    public DateTime DateOfCreating { get; set; }
    public DateTime DateOfProcessing { get; set; }
    public DateTime DateOfExecution { get; set; }

    //here is something incorrect
    public int CreatorId { get; set; }
    public int ManagerId { get; set; }
    public int ExecutorId { get; set; }
    public virtual User Creator { get; set; }
    public virtual User Manager { get; set; }
    public virtual User Executor { get; set; }

    public bool IsProcessed { get; set; }
    public bool IsExecuted { get; set; }
    public bool IsExecutionConfirmed { get; set; }
}

【问题讨论】:

  • 不知道你问的是什么人!你想让它做什么?
  • 为什么不正确?
  • 试着更清楚你的要求,希望你投票旁边的负面标志会消失。如果你问我认为你在问什么,你应该能够在你的 OnModelCreating 方法中在你的上下文中使用流利的 API 来指定它。
  • 语言能力差。我会更认真地学习英语。

标签: c# entity-framework postgresql ef-code-first


【解决方案1】:

我怀疑你必须告诉Entity Framework 这三个属性应该用作数据库中的外键。

由于它们具有非常规名称(EF 不会自动将它们识别为外键),您可以通过在它们上设置 ForeignKey 属性并指定它们是外键值的导航属性来帮助它理解。

[ForeignKey("Creator")]
public int CreatorId { get; set; }

[ForeignKey("Manager")]
public int ManagerId { get; set; }

[ForeignKey("Executor")]
public int ExecutorId { get; set; }

public virtual User Creator { get; set; }
public virtual User Manager { get; set; }
public virtual User Executor { get; set; }

【讨论】:

  • 我在你回答的同时找到了解决办法。是的,这正是我所需要的。谢谢。
猜你喜欢
  • 1970-01-01
  • 2014-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多