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

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)1.Initialize()
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
at System.Data.Entity.Internal.Linq.InternalSet1.get_InternalContext()1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
at System.Data.Entity.Internal.Linq.InternalSet
at System.Data.Entity.Internal.Linq.InternalSet1.Add(Object entity)1.Add(TEntity entity)
at System.Data.Entity.DbSet
at demoMVVM.MainWindow.btnAdd_Click(Object sender, RoutedEventArgs e) in d:\LuuTru\CSharp\WPF Application\TestMVVM\demoMVVM\MainWindow.xaml.cs:line 48