2

私は MVC の初心者で、EF-database-first を使用して MVC4 アプリケーションを作成しました。データベースに外部キー定義が含まれておらず、追加できません (データベースを所有していません)。データベースの 2 つのクラスの例を次に示します。

public partial class Allocation
{
    public int AllocID { get; set; }
    public int DeptID { get; set; }
    public decimal AllocationPercent { get; set; }
}

public partial class Department
{
    public int DeptID { get; set; }
    public string DeptName { get; set; }
    public string Account { get; set; }
}

デフォルトの割り当てインデックス ページには、部門 ID が表示されます。代わりに部門名を表示したい。ナビゲーション プロパティなしでこれを行うにはどうすればよいですか?

私は試した

public class AllocationController : Controller
{
    private Entities db = new Entities();

    //
    // GET: /Allocation/

    public ActionResult Index()
    {
        return View(db.Allocation.Include(d => d.DeptID).ToList());
    }
...

しかし、これによりエラーが発生します (「指定されたインクルード パスは無効です。EntityType 'TESTModel.Allocation' は、'DeptID' という名前のナビゲーション プロパティを宣言していません。」)...

ナビゲーション プロパティを使用せずにeager-loadingまたはexplicit-loadingをコーディングする方法がわからないため、この質問が生じました。効率的には、関連する情報をどの方法でロードするかは問題ではないと思います。

4

2 に答える 2

1

フィールドが存在し、エンティティが参照整合性を念頭に置いてデータベースに配置されている限り、データベースに定義を含める必要はありません。あなたがする必要があるのは、エンティティフレームワークに関係について知らせることだけです。これは、virtual「ナビゲーションプロパティ」を作成するためのキーワードを使用して行われます。

public partial class Allocation
{
 public int AllocID { get; set; }
 public int DeptID { get; set; }
 public decimal AllocationPercent { get; set; }
 public virtual Department Department { get; set; } /* this is your nav property */
}

public partial class Department
{
 public int DeptID { get; set; }
 public string DeptName { get; set; }
 public string Account { get; set; }
}

今、あなたはすることができます:

db.Allocation.Include(a => a.Department).ToList()

外部キー定義を使用する必要があるエラーがある可能性があります(私はそうは思いませんが)。この場合、ナビゲーションプロパティを次のように装飾する必要があります

[ForeignKey("DeptID")]
public virtual Department Department { get; set; }

この方法で試すこともできます。

 public int AllocID { get; set; }
 [ForeignKey("Department")]
 public int DeptID { get; set; }
 public decimal AllocationPercent { get; set; }
 public virtual Department Department { get; set; }
于 2013-01-31T00:51:53.960 に答える
0

ナビゲーションプロパティを使用すると、TravisJの答えはあなたが必要とするものです。ナビゲーションプロパティを使用したくない場合は、DBコンテキストにと呼ばれるセットがあると仮定するとDepartments、次のように実行できます。

var deptId = db.Allocation.DeptID;
var departments = db.Departments.Where(p => p.DeptID == deptId);
return View(departments.ToList());
于 2013-01-31T01:00:47.030 に答える