首页 > 解决方案 > 如何正确连接数据库与 MVC web 项目,获取值不能为空。参数名称:entitySet'

问题描述

当我向 DbSet 添加一些内容时,我收到了我描述的错误,我导入了我需要的所有内容以及我在 stackoverflow 上阅读的一些内容,当我制作控制台应用程序时,我没有问题地连接它,但由于某种原因,它无法使用网络项目。

这是我的 Web.config 文件的一部分,我在下面提供了其余的类

<add name="MyDBContext" providerName="System.Data.SqlClient" connectionString="Server=Batonja-PC; Database=ProjekatBaza; user=sa;password=stoka123"/>

公共课 Korisnik {

public Korisnik(){

}

public override bool Equals(object obj)
{
    Korisnik gost = (Korisnik)obj;
    if(Username == gost.Username)
    {
        return true;
    }
    return false;
}

public override int GetHashCode()
{
    return Username.GetHashCode();
}

public override string ToString()
{
    return Ime + " " + Prezime + " " + Pol.ToString() + " " + Username + " " + Password;

}



public Korisnik(string ime, string password, Pol? pol, string prezime, string username)
{
    Ime = ime;
    Password = password;
    Pol = pol;
    Prezime = prezime;
    Username = username;
    Uloga = Roles.Domacin;
}



public string Ime { get; set; }

public string Password { get; set; }

public Pol? Pol { get; set; }

public string Prezime { get; set; }

public Roles? Uloga { get; set; }

[Key]
public string Username { get; set; }

}

public class MyDBContext : DbContext
{
    public DbSet<Domacin> Domacini { get; set; }
    public DbSet<Gost> Gosti { get; set; }
    public DbSet<Administrator> Administratori { get; set; }
    public DbSet<Rezervacija> Rezervacije { get; set; }
    public DbSet<Komentar> Komentari { get; set; }
    public DbSet<Apartman> Apartmani { get; set; }
    public DbSet<Korisnik> Korisnici { get; set; }

    public MyDBContext(): base("MyDBContext")
    {

    }


}

公共行动结果索引(){

        UcitajAdmine(@"D:\FAKS\WEB\Projekat\Projekat\Projekat\Administratori.txt");

        using (var context = new MyDBContext())
        {
            Korisnik korisnik = new Korisnik("Mile","stokan",Pol.Muski,"MIlic","Milo");
            try
            {
                context.Korisnici.Add(korisnik);
            }catch(SqlException ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
            context.SaveChanges();
        }

            return View();
    }

标签: webmodel-view-controllerentity-framework-6entity

解决方案


推荐阅读