簡體   English   中英

實體框架教程(簡單的代碼優先示例)不起作用

[英]Entity Framework tutorial (simple code-first example) doesn't work

今天,我開始關注Entity Framework教程: 簡單代碼優先示例

我想我擁有應有的一切,但我的應用程序無法正常工作。

這是我的代碼:

public class Student
{
    public Student()
    {

    }
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public DateTime DateOfBirth { get; set; }
    public byte[] Photo { get; set; }
    public decimal Height { get; set; }
    public float Weight { get; set; }

    public Standard Standard { get; set; }
}

public class Standard
    {
        public Standard()
        {

        }
        public int StandardId { get; set; }
        public string StandardName { get; set; }

        public ICollection<Student> Students { get; set; }
    }

public class SchoolContext : DbContext
{
    public SchoolContext()
        : base()
    {

    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Standard> Standards { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        using (var ctx = new SchoolContext())
        {
            Student stud = new Student() { StudentName = "New Student" };

            ctx.Students.Add(stud);
            ctx.SaveChanges();
            Console.WriteLine("done.");
        }
    }
}

它的構建沒有任何錯誤或警告,可以啟動控制台,但是它不會過去

ctx.Students.Add(stud);

它還沒有創建任何數據庫和表。

我遵循了教程中的所有內容,卻不知道為什么它不起作用。

編輯:它確實在60秒后引發錯誤(其他信息以波蘭語顯示,我現在真的不怎么在VS中將其更改為英語):EntityFramework中發生了類型為'System.Data.SqlClient.SqlException'的未處理異常。 dll文件

附加信息:SQL Server程序。SQL Server。 Niemożnaodnaleźćserwera lub jest onniedostępny。 SQL Server的SQL Server編程。 (提供者:SQL網絡接口,錯誤:26-Błądpodczas lokalizowaniaokreślonegoserwera /wystąpienia)

而且我必須添加,我使用的是Visual Studio 2013社區和此版本的Visual Studio中包含的localDB。

您是否嘗試過將導航屬性設置為虛擬? 另外,如果要將這兩個Student類和Standard類相互連接,則需要定義外鍵。

例如,將其添加到Student類中:

public class Student
{
    public Student()
    {

    }
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public DateTime DateOfBirth { get; set; }
    public byte[] Photo { get; set; }
    public decimal Height { get; set; }
    public float Weight { get; set; }

    public int StandartID{get;set;}//foreign key references Standard(StandardId)
    public virtual Standard Standard { get; set; }//navigation property
}

在Stadart類中,這是:

public class Standard
{
    public Standard()
    {

    }
    public int StandardId { get; set; }
    public string StandardName { get; set; }

    public int StudentID{get;set;}//foreign key references Student(StudentID)
    public virtual ICollection<Student> Students { get; set; }
}

希望這個能對您有所幫助

暫無
暫無

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

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