与EF codeFirst和SqlCe4唯一约束 [英] Unique constraint with EFCodeFirst and SqlCe4

查看:374
本文介绍了与EF codeFirst和SqlCe4唯一约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写使用实体框架code首先和SqlCe4的ASP.net应用MVC3

I'm writing an ASP.net MVC3 application using Entity Framework Code First and SqlCe4.

我一直在设计几款车型,发现一个正在变成很有趣。这是我到目前为止有:

I have been designing several models, and found one that is turning out to be interesting. This is what I have so far:

public class Preference
    {
        public int PreferenceId { get; set; }

        [Required]
        public int StudentId { get; set; }
        public virtual Student Student { get; set; }

        [Required]
        public int PresentationId { get; set; }
        public virtual Presentation Presentation { get; set; }

        [Required]
        public int Rank { get; set; }
    }

我然而,需要一个唯一的约束或索引,因为对于一个特定的学生,我希望他们要有preferences的列表,但presentationId需要为每个学生独特。有没有办法通过code首先还是一些验证属性来做到这一点?

I however, need a unique constraint or index, because for a particular student, I want them to have to have a list of preferences, but the PresentationId needs to be unique for each student. Is there a way to do this via Code First or some validation attribute?

这听起来像我要下了许多的分支与preference对象是中介一对多的关系,要添加等级属性。不过,我似乎无法找到如何确保该值是唯一的。是最好的方式真的手动只是EF之外增加一个唯一索引数据库?

This sounds like I'm going down the branch of a many to many relationship with the Preference object being an intermediary, to add the Rank property. However, I can't seem to find how to make sure that the values are unique. Is the best way really to manually just add a unique index to the database outside of EF?

推荐答案

去什么Eranga说的话,我最终使它同样的工作,但像这样的:

Going with what Eranga was saying, I ended up making it work similarly, but like this:

我用下面的code在我的DataContext类:

I used the following code in my DataContext class:

public class StudentRegistrationContext : DbContext
{
    public StudentRegistrationContext()
    {
        Database.SetInitializer(new StudentRegistrationDatabaseInitializer());
    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Teacher> Teachers { get; set; }
    public DbSet<Presenter> Presenters { get; set; }
    public DbSet<Presentation> Presentations { get; set; }
}

在数据库初始化器类,我用了以下内容:

In the Database Initializer class, I used the following:

public class StudentRegistrationDatabaseInitializer : DropCreateDatabaseIfModelChanges<StudentRegistrationContext>
{
    protected override void Seed(StudentRegistrationContext context)
    {
        base.Seed(context);
        context.Database.ExecuteSqlCommand("CREATE UNIQUE INDEX UX_Preferences_StudentId_PresentationId ON Preferences (StudentId, PresentationId)");
    }
}

这篇关于与EF codeFirst和SqlCe4唯一约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆