2017-01-17 4 views
0

私はRecipe ModelRecipeCategoryというモデルを持つAsp.net MVCアプリケーションを作成しています。レシピモデルforeign keyRecipeCategoryのモデルが含まれています。私はEntity Frameworkが初めてです。私はcode firstエンティティフレームワークのアプローチを使用しています。ASP.netでの外部キー関係の作成MVC Entity Frameworkコード

public class RecipeCategory 
{ 
    public int RecipeCategoryID { get; set; } 
    public string Name { get; set; } 
    public List<Recipe> Recipe { get; set; } 
} 

と私は以下のようなレシピモデルクラスを持っている: 私はrecipeCategoryモデルは以下のように定義している私が欲しいもの

public class Recipe 
{ 
    public int ID { get; set; } 
    public string Title { get; set; } 
    public string Description { get; set; } 

    public int RecipeCategoryID { get; set; } 
    public RecipeCategory RecipeCategory { get; set; } 
} 

:新しいレシピを作成している間

  1. 、私が欲しいですRecipeCategoriesを選択するためのUIのカテゴリのリストを取得できません。

  2. 両方のテーブル間に適切な外部キーを設定したい。この問題を解決するのを手伝ってください。

答えて

1

あなたの関係は正しいです。より多くの改善のために私はあなたのICollectionの複数の名前がレシピの代わりにレシピを意味し、リストをICollectionに置き換えることを提案します。

レシピカテゴリを取得できないと言ってきたので、今すぐ使用したいコードを投稿してください。

1. DbContextから継承したコンテキストクラスを作成し、DbSetsで両方のエンティティを定義しておく必要があります。

public class YourContext: DbContext 
{ 
    public YourContext(): 
     base("yourConnectionString") 
    { 
    } 

    public DbSet<Recipe> Recipes { get; set; } 
    public DbSet<RecipeCategory> RecipeCategories { get; set; } 
} 

そのあとは、このようにあなたのカテゴリを返すことができます:あなたは、テーブルに外部キー制約を配置する必要があり

public IEnumerable<RecipeCategory> Get() 
{ 
    YourContext context = new YourContext(); 
    return context.RecipeCategories; 
} 
+0

私はレシピのモデルのビューを作成し、作成ビューで、私は、リストからカテゴリを選択するためのオプションを持っていないのですか?私の関係が正しいとすれば、どうすればいいですか? –

+0

私は別々のレシピカテゴリを取得する必要がありますか?私は強く型付けされたモデルのレシピからビューを作成していますか?作成ビューには表示されませんか? –

+0

さて、あなたの作成アクションメソッドでは、データベースからRecipeCategoriesのリストを取得し、それをViewBagに保存する必要があります。次に、ビューで、ビューバックからドロップダウンをレンダリングできます。 http://stackoverflow.com/questions/16594958/how-to-use-a-viewbag-to-create-a-dropdownlistおよびhttp://www.compilemode.com/2016/01/bind- dropdownlist-using-viewbag-in-asp-net-mvc.html @DelicateHiba –

0
public class RecipeCategory 
{ 
[Key][DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)] 
    public int RecipeCategoryID { get; set; } 
    public string Name { get; set; } 
    public List<Recipe> Recipe { get; set; } 
} 


public class Recipe 
{ 

    public int ID { get; set; } 

    public virtual int RecipeCategoryID { get; set; } 

    [ForeignKey("RecipeCategoryID ")] 
    public virtual ApplicationUser ApplicationUser { get; set; } 

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

    public int RecipeCategoryID { get; set; } 
    public RecipeCategory RecipeCategory { get; set; } 
} 
1

。あなたのケースでは

[ForeignKey("ObjName")] 

public class Recipe 
{ 
    public int ID { get; set; } 
    public string Title { get; set; } 
    public string Description { get; set; } 
    [ForeignKey("RecipeCategory")] 
    public int RecipeCategoryID { get; set; } 
    public RecipeCategory RecipeCategory { get; set; } 
} 
関連する問題