繁体   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