0

i find the problem when i tried to create a controller for sql server table,not code-first(localdb),and i check the connectionString ,but i think i hasn't mistakes on it

for safety ,i hide the machine-name,username and password

One or more validation errors were detected during model generation:

DB2Ex.Model.Student: : EntityType 'Student' has no key defined. Define the key for this EntityType.

Students: : EntityType 'Students' has no key defined. Define the key for this EntityType.

public class Student
{
    public int xh { get; set; }
    public string xm { get; set; }
    public string xb { get; set; }
    public string csrq { get; set; }
    public string jg { get; set; }
    public string sjhm { get; set; }
    public string yxh { get; set; }
    public string mm { get; set; }
}
public class StudentDBContext : DbContext
{
    public StudentDBContext()
        : base("schoolDB")
    {
    }
    public DbSet<Student> Students { get; set; }
}

<add name="schoolDB" connectionString="Data Source=DESKTOP-*****;Initial Catalog=school;Persist Security Info=True;User ID=***;Password=***" providerName="System.Data.SqlClient" />
1
  • None of these are controllers - and the error isn't about a controller - it tells you there is no key defined for your Student class. Perhaps you need to define one? Commented May 21, 2017 at 15:25

2 Answers 2

3

Assuming xh is the key field in the database, you need to define it in your Student model too:

public class Student
{
    [Key]
    public int xh { get; set; }
    public string xm { get; set; }
    public string xb { get; set; }
    public string csrq { get; set; }
    public string jg { get; set; }
    public string sjhm { get; set; }
    public string yxh { get; set; }
    public string mm { get; set; }
}
Sign up to request clarification or add additional context in comments.

2 Comments

i will try it now
it really works ,but i cant see the db data in tables,maybe it's different from the code-first mode
0

I find the way to solve it

-Models
-Create a "ADO.Net Model"
-Choose the sql server db
-Dont forget choose "create the default connectionstring"

Then create a controller for the db.tables and the Dbcontext that hava been created by VS

And i will get the similar views like choosing the code-first way:create new,details,delete and other options

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.