簡體   English   中英

首先在ASP.net MVC實體框架代碼中創建外鍵關系

[英]Create Foreign Key Relationship in ASP.net MVC Entity Framework Code First

我正在創建其中具有Recipe ModelRecipeCategory模型的Asp.net MVC應用程序。 我希望配方模型包含RecipeCategory模型的foreign key 我是實體框架的新手。 我正在使用實體框架的code first方法。 我有recipeCategory定義的recipeCategory模型:

public class RecipeCategory
{
    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 string Title { get; set; }
    public string  Description { get; set; }

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

我想要的是:

  1. 在創建新的配方時,我希望UI中的類別列表選擇RecipeCategories,但我無法獲取。

  2. 我想在兩個表之間正確建立外鍵。 請幫我解決這個問題

您的關系是正確的。 為了獲得更多改進,我建議您為ICollection使用復數名稱,即用Recipes代替Recipe,並將List替換為ICollection。

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

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; }
}

現在說到要點,就像您說的那樣,您無法獲得RecipeCategories,因此,請您能為此發布您的代碼嗎?

它應該是這樣的: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;
}

您需要在表中放置外鍵約束。

[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; }
}
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; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM