1

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

2
  • What does exception erorr message says? Commented Jun 24, 2014 at 4:07
  • Your model data are violate constraint on your model definition, therefore this exception occur. See inner exception for more details Commented Jun 24, 2014 at 4:14

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

12 Comments

Thank you very much, It work correctly when i remove [ForeignKey(Name="GroupID")] public virtual Group Group { get; set; }c because it do not know "Name" in [ForeignKey(Name="GroupID")]
so, if i want to setup this app to another computer. Do i need to add connectionString and convert to Entity FrameWork with existing database ? or just copy mdf file ?
What kind of database you're using? SQL Server or SQL Server Compact? If you're using SQL Server, you only need to point EF to your existing database via connectionString, but if you're using SQL Server Compact, you have to copy mdf file to App_Data folder on the other computer
Sorry, I made a mistake, please update your foreign key declaration as in the answer, you will need it in order to enable EF Lazy Loading
How can i define ForeignKey have same name with attribute in that class. For example: in class SinhVien we have attribute "Name" but if i want to have ForeignKey with Name in Group. How can i do it ?
|

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.