简体   繁体   English

C#实体框架代码首次创建控制器

[英]C# Entity Framework Code First-create controller

I want to learn Entity Framework Code First but I can't solve a problem. 我想先学习实体框架代码,但不能解决问题。 When I want to create a controller (form Model class Anime using AnimeDbContext) I have error Image Of Error 当我想创建控制器(使用AnimeDbContext的Model类动漫)时,出现错误Image Of Error

I see that is some problem with Foreign Key but I dont know why. 我看到外键存在一些问题,但我不知道为什么。 Here is a code of class Anime 这是动漫类的代码

namespace MyBD.Models
{
    [Table("Anime")]

    public class Anime
    {


        [Key] // ustawiamy klucz główny tabeli
        public int Id { get; private set; }
        [Required]
        public string Title { get; private set; }
        public string Description { get; private set; }

        public Anime(int id=0, string title="New", string description="Description") 
        {
            this.Id = id;
            this.Title = title;
            this.Description = description;
        }



        public virtual ICollection<CommentAnime>  Comments { get; set; }


    }

}

And class AnimeComment 和类动漫评论

    namespace MyBD.Models
{
    [Table("CommentAnime")]
    public class CommentAnime
    {
        [Key]
        public int Id { get; private set; }
        [ForeignKey("anime")] // ustawiamy klucz obcy
        [Required]
        public int AnimeId { get; set; }
        public string Opinion { get; private set; }
        public int Mark { get; private set; }

        public CommentAnime(int id=0, string opinion="My Opinion", int mark=0)
        {
            this.Id = id;
            this.Opinion = opinion;
            this.Mark = mark;
        }

        public virtual Anime anime { get; set; }

Phillip's answer already cover most of the changes you need in your model. Phillip的答案已经涵盖了您模型中所需的大多数更改。 I just want to work more on that and provide you with how you can configurate your dbContext class using the FluentAPI. 我只想在此方面做更多的工作,并向您提供如何使用FluentAPI配置dbContext类的方法。 This way you can skip the Data Annotation attributes on your classes: 这样,您可以跳过类上的“数据注释”属性:

Anime Class: 动漫类:

public class Anime
{
    public int Id { get; set; }
    public string Title { get; set;}
    public string Description { get; set; }

    public virtual ICollection<CommentAnime> Comments { get; set; }
}

public class CommentAnime
{

    public int Id { get; set; }
    public string Opinion { get; set; }
    public int Mark { get; set; }

    public int AnimeId { get; set; }
    public virtual Anime anime { get; set; }
}

AnimeDbContext class AnimeDbContext类

//Program Table
//Title Field
modelBuilder.Entity<Anime>()
            .Property(t => t.Title)
            .HasColumnType("varchar")
            .HasMaxLength(120) //define some Length..
            .IsRequired(); //Will be translated as Not Null


//CommentAnime
//Opinion Field
modelBuilder.Entity<CommentAnime>()
            .Property(t => t.Opinion)
            .HasColumnType("varchar")
            .HasMaxLength(120) //define some Length..
            .IsRequired(); //Will be translated as Not Null


//Configuring the One-to-Many Relationship

modelBuilder.Entity<CommentAnime>()
            .HasRequired(t => t.Anime)
            .WithMany(x => x.Comments)
            .HasForeignKey(t => t.AnimeId);

If you want to have a nullable ForeinKey in CommentAnime, you can use HasOptional instead of HasRequired . 如果要在CommentAnime中使用可为空的ForeinKey,则可以使用HasOptional代替HasRequired Note that you also don't need to create configuration for your Id columns, since EF use naming conventions 请注意,由于EF使用命名约定 ,因此您也不需要为Id列创建配置。

This way your POCO classes are clean and independent of any EF configuration. 这样,您的POCO类是干净的,并且与任何EF配置无关。 All database modeling are centralized in the AnimeDbContext class. 所有数据库建模都集中在AnimeDbContext类中。 I personally find this to be the best approach since you avoid poluting your classes with attributes, but, I guess this is just a personal thing. 我个人认为这是最好的方法,因为您避免使用属性来污染类,但是,我想这只是个人的事情。

In entity framework I've found that if any property in your class is called "Id", in upper or lower case, "ID" or "id", it will reference that as the Primary Key. 在实体框架中,我发现如果类中的任何属性称为“ Id”,则以大写或小写形式称为“ ID”或“ id”,它将把它称为主键。 So you don't need the [Key] Data annotation. 因此,您不需要[Key]数据注释。

You also don't need the [Table()] data annotation, as EF will default to the class name for the table name. 您也不需要[Table()]数据注释,因为EF将默认使用表名的类名。

You also don't need to put in a Public Constructor, as you can use the View to set placeholder text. 您也不需要放入公共构造函数,因为您可以使用“视图”设置占位符文本。 You can use the default constructor for default values, like setting the date created, see Anime class for example. 您可以将默认构造函数用于默认值,例如设置创建日期,例如,请参见Anime类。

See below for your new classes. 请参阅下面的新课程。

public class Anime
{
    public Anime()
    {
        Description = "This is a desciption";
        DateCreated= DateTime.UtcNow;

    }

    public int Id { get; set; }
    [Required]
    public string Title { get; set; }
    public string Description { get; set; }
    public DateTime DateCreated { get; set; }      


    public virtual ICollection<CommentAnime>  Comments { get; set; }


}

When doing joins in EF by referencing the parent table as a virtual and using the "nameId" EF again will automatically work it out for you. 通过将父表引用为虚拟表并使用“ nameId”在EF中进行联接时,再次使用EF会自动为您解决。

public class CommentsAnime
{
    public int Id { get; set; }
    public int AnimeId { get; set; } //Using the virtual table name
    public string Opinion { get; private set; }
    public int Mark { get; private set; }

    public virtual Anime Anime { get; set; }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM