1
votes

I am studying about Entity Framework and I can do it with code first + existing database. However, when I try to create a new database with code first, it doesn't work.

Can you help me correct my code ?

public class QuanLySinhVien : DbContext
{
    public virtual DbSet<SinhVien> SinhViens { get; set; }
    public virtual DbSet<Group> Groups { get; set; }
}

public class SinhVien
{
    public int SinhVienId { get; set; }
    public string Name { get; set; }    
    public string Address { get; set; }
    public DateTime BirthDay { get; set; }
    public int GroupId { get; set; }
    public virtual Group Group { get; set; }
}

public class Group
{
    public int GroupId { get; set; }
    public string Name { get; set; }       
}

and this is create code

var db = new QuanLySinhVien();          
        var sinhvien = new SinhVien { Name = "Test Name", Address="Address", BirthDay=DateTime.Now };
        db.SinhViens.Add(sinhvien);
        db.SaveChanges();

this is message

enter image description here

System.Data.Entity.ModelConfiguration.ModelValidationException: One or more validation errors were detected during model generation:

demoMVVM.SinhVien: : EntityType 'SinhVien' has no key defined. Define the key for this EntityType.
SinhViens: EntityType: EntitySet 'SinhViens' is based on type 'SinhVien' that has no keys defined.

at System.Data.Entity.Core.Metadata.Edm.EdmModel.Validate()
at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.Initialize()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet
1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet1.get_InternalContext()
at System.Data.Entity.Internal.Linq.InternalSet
1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
at System.Data.Entity.Internal.Linq.InternalSet1.Add(Object entity)
at System.Data.Entity.DbSet
1.Add(TEntity entity)
at demoMVVM.MainWindow.btnAdd_Click(Object sender, RoutedEventArgs e) in d:\LuuTru\CSharp\WPF Application\TestMVVM\demoMVVM\MainWindow.xaml.cs:line 48

1
What does exception erorr message says? - Petr Abdulin
Your model data are violate constraint on your model definition, therefore this exception occur. See inner exception for more details - Doan Cuong

1 Answers

3
votes

Import System.ComponentModel.DataAnnotations

Change your model as follow:

public class SinhVien
{
    [Key]
    public int SinhVienId { get; set; }
    public string Name { get; set; }    
    public string Address { get; set; }
    public DateTime BirthDay { get; set; }
    public int GroupId { get; set; }
    [ForeignKey("GroupId")]
    public virtual Group Group { get; set; }
}
public class Group
{
    [Key]
    public int GroupId { get; set; }
    public string Name { get; set; }       
}

You got the exception because you haven't defined primary key for your model. By default, EF take Id property as primary key, but if you use another name for your key, you have to explicit delcare it (in your case is SinhVienId and GroupId

UPDATE

You can define database name in connectionString inside your app.config/web.config then pass connectionString name to DbContext constructor like this:

<add 
name="connectionStringName" 
connectionString="Data Source=|DataDirectory|\yourdbfile.mdf" 
providerName="System.Data.SqlClient" />

and DbContext constructor:

public class ModelContext : DbContext
{
    public ModelContext()
        : base("connectionStringName")
    {
    }
}

Note that |DataDirectory| will point to your App_Data folder