MVC3代码优先迁移(表关系不起作用) [英] MVC3 Code First Migrations (table relationship not working)

查看:68
本文介绍了MVC3代码优先迁移(表关系不起作用)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的编程社区,



在我的MVC3网络应用程序中使用代码优先迁移时,我遇到以下问题。



患者模型:



Dear programming community,

I have the following problem when using code first migrations in my MVC3 web application.

Patient Model:

public class PatientModel
    {
        [Key]
        [Required(ErrorMessage = "Patient ID is required!")]
        [Display(Name = "Patient ID:")]
        public virtual int Patient_id { get; set; }

        //[Display(Name = "Patient Ward:")]
        //public virtual int Patient_ward_id { get; set; }

        public WardModel Ward { get; set; }

        //[Display(Name = "Patient Salutation:")]
        //public virtual int Patient_salutation_id { get; set; }

        public SalutationModel Salutation { get; set; }
    }







称呼模型:






Salutation Model:

public class SalutationModel
    {
        [Key]
        [Display(Name = "Salutation ID:")]
        public virtual int Salutation_id { get; set; }

        [Display(Name = "Salutation Name:")]
        public virtual string Salutation_name { get; set; }

        //// one to many relationship
        //public virtual ICollection<PatientModel> Patients { get; set; }
    }







正如你所看到的我定义了两者之间的关系那2张桌子正确。一个称呼可以属于许多患者。





查看:






As you can see i defined the relationship between those 2 tables properly. One salutation can belong to many patients.


View:

@(Html.Kendo().Window()
    .Name("window")
    .Title("Details of " + Model.Patient_firstname + " " + Model.Patient_lastname)
    .Content(@<text>
    <fieldset>
        <legend>Patient</legend>

        <div class="display-label">
            @Html.LabelFor(model => model.Salutation.Salutation_name)
        </div>
        <div class="display-field">
            @Html.DisplayFor(model => model.Salutation.Salutation_name)
        </div>

        <div class="display-label">
            @Html.LabelFor(model => model.Patient_firstname)
        </div>
        <div class="display-field">
            @Html.DisplayFor(model => model.Patient_firstname)
        </div>





在我看来,我正在通过患者模型检索特定患者的称呼名称,但我没有得到任何回报。 (我从患者那里得到其余的数据没有问题)



PS:这对我来说很有用但是因为我不行使用数据库迁移,所以我的猜测是我在数据库迁移中没有做正确的事情。 (数据{mr,mrs}肯定在称呼表中,但我不能为特定患者检索它。





这是我的DBEntities课程:





In my view i am retrieveing a salutation name for a specific patient through patient model but i am not getting anything back. ( i am getting the rest of the data from the patient tbl with no problems )

PS: This was working for me before but it doesn''t work since i used DB migration so my guess is that I am not doing something right in DB migration. ( The data {mr,mrs} is in the salutation table for sure but i can''t retrieve it for a specific patient )


Here is my DBEntities class:

public class MyDBEntities : DbContext
{
    public DbSet<PatientModel> Patients { get; set; }
    public DbSet<DoctorModel> Doctors { get; set; }
    public DbSet<NurseModel> Nurses { get; set; }
    public DbSet<SalutationModel> Salutations { get; set; }
    public DbSet<WardModel> Wards { get; set; }
}









+这是我的迁移类(由add-migration命令生成):







+ Here is my migration class (generated by "add-migration" command) :

using System;
using System.Data.Entity.Migrations;

public partial class Initial : DbMigration
{
    public override void Up()
    {
        CreateTable(
            "dbo.PatientModels",
            c => new
                {
                    Patient_id = c.Int(nullable: false, identity: true),
                    Patient_firstname = c.String(nullable: false, maxLength: 50),
                    Patient_middlename = c.String(maxLength: 50),
                    Patient_lastname = c.String(nullable: false, maxLength: 50),
                    Patient_sex = c.String(nullable: false, maxLength: 6),
                    Patient_home_number = c.Int(),
                    Patient_phone_number = c.Int(nullable: false),
                    Patient_address_line1 = c.String(maxLength: 50),
                    Patient_address_line2 = c.String(maxLength: 50),
                    Patient_city = c.String(maxLength: 50),
                    Patient_country = c.String(maxLength: 50),
                    Patient_dob = c.DateTime(nullable: false),
                    Ward_Ward_id = c.Int(),
                    Salutation_Salutation_id = c.Int(),
                })
            .PrimaryKey(t => t.Patient_id)
            .ForeignKey("dbo.WardModels", t => t.Ward_Ward_id)
            .ForeignKey("dbo.SalutationModels", t => t.Salutation_Salutation_id)
            .Index(t => t.Ward_Ward_id)
            .Index(t => t.Salutation_Salutation_id);

        CreateTable(
            "dbo.WardModels",
            c => new
                {
                    Ward_id = c.Int(nullable: false, identity: true),
                    Ward_name = c.String(nullable: false, maxLength: 50),
                    Ward_manager_id = c.Int(nullable: false),
                    Ward_capacity = c.Int(nullable: false),
                    Ward_speciality = c.String(nullable: false, maxLength: 50),
                    Ward_status = c.String(),
                    Ward_moto = c.String(maxLength: 50),
                    Doctor_Doctor_id = c.Int(),
                })
            .PrimaryKey(t => t.Ward_id)
            .ForeignKey("dbo.DoctorModels", t => t.Doctor_Doctor_id)
            .Index(t => t.Doctor_Doctor_id);

        CreateTable(
            "dbo.DoctorModels",
            c => new
                {
                    Doctor_id = c.Int(nullable: false, identity: true),
                    Doctor_username = c.String(nullable: false, maxLength: 50),
                    Doctor_firstname = c.String(nullable: false, maxLength: 50),
                    Doctor_middlename = c.String(),
                    Doctor_lastname = c.String(nullable: false, maxLength: 50),
                    Doctor_speciality = c.String(nullable: false, maxLength: 50),
                    Doctor_sex = c.String(),
                    Doctor_home_number = c.Int(),
                    Doctor_phone_number = c.Int(nullable: false),
                    Doctor_address_line1 = c.String(nullable: false, maxLength: 50),
                    Doctor_address_line2 = c.String(nullable: false, maxLength: 50),
                    Doctor_city = c.String(nullable: false, maxLength: 50),
                    Doctor_country = c.String(nullable: false, maxLength: 50),
                    Doctor_dob = c.DateTime(nullable: false),
                    Doctor_bleep_id = c.Int(nullable: false),
                    Image_name = c.String(),
                    Image_size = c.Int(nullable: false),
                    Image_bytes = c.Binary(),
                })
            .PrimaryKey(t => t.Doctor_id);

        CreateTable(
            "dbo.EquipmentModels",
            c => new
                {
                    Equipment_id = c.Int(nullable: false, identity: true),
                    Equipment_name = c.String(nullable: false, maxLength: 50),
                    Equipment_priority_id = c.Int(nullable: false),
                    Equipment_status_id = c.Int(nullable: false),
                    Equipment_quantity = c.Int(nullable: false),
                    Doctor_equipment_id = c.Int(nullable: false),
                    Doctor_equipment_priority = c.Int(nullable: false),
                    Doctor_equipment_status = c.Int(nullable: false),
                    Doctor_Doctor_id = c.Int(),
                    Priority_Priority_id = c.Int(),
                    Status_Status_id = c.Int(),
                })
            .PrimaryKey(t => t.Equipment_id)
            .ForeignKey("dbo.DoctorModels", t => t.Doctor_Doctor_id)
            .ForeignKey("dbo.EquipmentPriorityModels", t => t.Priority_Priority_id)
            .ForeignKey("dbo.EquipmentStatusModels", t => t.Status_Status_id)
            .Index(t => t.Doctor_Doctor_id)
            .Index(t => t.Priority_Priority_id)
            .Index(t => t.Status_Status_id);

        CreateTable(
            "dbo.EquipmentPriorityModels",
            c => new
                {
                    Priority_id = c.Int(nullable: false, identity: true),
                    Priority_name = c.String(),
                })
            .PrimaryKey(t => t.Priority_id);

        CreateTable(
            "dbo.EquipmentStatusModels",
            c => new
                {
                    Status_id = c.Int(nullable: false, identity: true),
                    Status_name = c.String(),
                })
            .PrimaryKey(t => t.Status_id);

        CreateTable(
            "dbo.NurseModels",
            c => new
                {
                    Nurse_id = c.Int(nullable: false),
                    Nurse_ward_id = c.Int(nullable: false),
                    Nurse_username = c.String(),
                    Nurse_firstname = c.String(),
                    Nurse_middlename = c.String(),
                    Nurse_lastname = c.String(),
                    Nurse_speciality = c.String(),
                    Nurse_home_number = c.Int(nullable: false),
                    Nurse_phone_number = c.Int(nullable: false),
                    Nurse_address_line1 = c.String(),
                    Nurse_address_line2 = c.String(),
                    Nurse_city = c.String(),
                    Nurse_country = c.String(),
                    Nurse_dob = c.DateTime(nullable: false),
                    Ward_Ward_id = c.Int(),
                })
            .PrimaryKey(t => new { t.Nurse_id, t.Nurse_ward_id })
            .ForeignKey("dbo.WardModels", t => t.Ward_Ward_id)
            .Index(t => t.Ward_Ward_id);

        CreateTable(
            "dbo.SalutationModels",
            c => new
                {
                    Salutation_id = c.Int(nullable: false, identity: true),
                    Salutation_name = c.String(),
                })
            .PrimaryKey(t => t.Salutation_id);

        CreateTable(
            "dbo.CareTeamModels",
            c => new
                {
                    Care_team_id = c.Int(nullable: false, identity: true),
                    Care_team_name = c.String(nullable: false),
                    Care_team_description = c.String(),
                })
            .PrimaryKey(t => t.Care_team_id);

        CreateTable(
            "dbo.TheatreModels",
            c => new
                {
                    Booking_id = c.Int(nullable: false, identity: true),
                    Patient_id = c.Int(nullable: false),
                    Care_team_id = c.Int(nullable: false),
                    Date_reserved = c.DateTime(nullable: false),
                    Reserve_code = c.Int(nullable: false),
                })
            .PrimaryKey(t => t.Booking_id);

        CreateTable(
            "dbo.ReportModels",
            c => new
                {
                    Report_id = c.Int(nullable: false, identity: true),
                    Report_title = c.Int(nullable: false),
                    Report_date_created = c.Int(nullable: false),
                    Report_date_updated = c.Int(nullable: false),
                    Report_file_attachement = c.Int(),
                    Doctor_Doctor_id = c.Int(),
                    Nurse_Nurse_id = c.Int(),
                    Nurse_Nurse_ward_id = c.Int(),
                })
            .PrimaryKey(t => t.Report_id)
            .ForeignKey("dbo.DoctorModels", t => t.Doctor_Doctor_id)
            .ForeignKey("dbo.NurseModels", t => new { t.Nurse_Nurse_id, t.Nurse_Nurse_ward_id })
            .Index(t => t.Doctor_Doctor_id)
            .Index(t => new { t.Nurse_Nurse_id, t.Nurse_Nurse_ward_id });

        CreateTable(
            "dbo.CareTeamNurseModels",
            c => new
                {
                    Care_team_id = c.Int(nullable: false, identity: true),
                    Nurse_id = c.Int(nullable: false),
                    Date_joined = c.Int(nullable: false),
                    Current_member = c.Boolean(nullable: false),
                })
            .PrimaryKey(t => t.Care_team_id);

        CreateTable(
            "dbo.CareTeamDoctorModels",
            c => new
                {
                    Care_team_id = c.Int(nullable: false, identity: true),
                    Doctor_id = c.Int(nullable: false),
                    Date_joined = c.Int(nullable: false),
                    Current_member = c.Boolean(nullable: false),
                })
            .PrimaryKey(t => t.Care_team_id);

        CreateTable(
            "dbo.ImageModels",
            c => new
                {
                    Image_id = c.Int(nullable: false, identity: true),
                    Image_name = c.String(),
                    Image_size = c.Int(nullable: false),
                    Image_title = c.String(),
                    Image_bytes = c.Binary(),
                })
            .PrimaryKey(t => t.Image_id);

    }

    public override void Down()
    {
        DropIndex("dbo.ReportModels", new[] { "Nurse_Nurse_id", "Nurse_Nurse_ward_id" });
        DropIndex("dbo.ReportModels", new[] { "Doctor_Doctor_id" });
        DropIndex("dbo.NurseModels", new[] { "Ward_Ward_id" });
        DropIndex("dbo.EquipmentModels", new[] { "Status_Status_id" });
        DropIndex("dbo.EquipmentModels", new[] { "Priority_Priority_id" });
        DropIndex("dbo.EquipmentModels", new[] { "Doctor_Doctor_id" });
        DropIndex("dbo.WardModels", new[] { "Doctor_Doctor_id" });
        DropIndex("dbo.PatientModels", new[] { "Salutation_Salutation_id" });
        DropIndex("dbo.PatientModels", new[] { "Ward_Ward_id" });
        DropForeignKey("dbo.ReportModels", new[] { "Nurse_Nurse_id", "Nurse_Nurse_ward_id" }, "dbo.NurseModels");
        DropForeignKey("dbo.ReportModels", "Doctor_Doctor_id", "dbo.DoctorModels");
        DropForeignKey("dbo.NurseModels", "Ward_Ward_id", "dbo.WardModels");
        DropForeignKey("dbo.EquipmentModels", "Status_Status_id", "dbo.EquipmentStatusModels");
        DropForeignKey("dbo.EquipmentModels", "Priority_Priority_id", "dbo.EquipmentPriorityModels");
        DropForeignKey("dbo.EquipmentModels", "Doctor_Doctor_id", "dbo.DoctorModels");
        DropForeignKey("dbo.WardModels", "Doctor_Doctor_id", "dbo.DoctorModels");
        DropForeignKey("dbo.PatientModels", "Salutation_Salutation_id", "dbo.SalutationModels");
        DropForeignKey("dbo.PatientModels", "Ward_Ward_id", "dbo.WardModels");
        DropTable("dbo.ImageModels");
        DropTable("dbo.CareTeamDoctorModels");
        DropTable("dbo.CareTeamNurseModels");
        DropTable("dbo.ReportModels");
        DropTable("dbo.TheatreModels");
        DropTable("dbo.CareTeamModels");
        DropTable("dbo.SalutationModels");
        DropTable("dbo.NurseModels");
        DropTable("dbo.EquipmentStatusModels");
        DropTable("dbo.EquipmentPriorityModels");
        DropTable("dbo.EquipmentModels");
        DropTable("dbo.DoctorModels");
        DropTable("dbo.WardModels");
        DropTable("dbo.PatientModels");
    }
}







=================================================================================



Here is my Configuration class:






=================================================================================

Here is my Configuration class:

{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
    }

    protected override void Seed(Maurxos.Models.MaurxosDBEntities context)
    {
        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet<T>.AddOrUpdate() helper extension method
        //  to avoid creating duplicate seed data. E.g.
        //
        //    context.People.AddOrUpdate(
        //      p => p.FullName,
        //      new Person { FullName = "Andrew Peters" },
        //      new Person { FullName = "Brice Lambson" },
        //      new Person { FullName = "Rowan Miller" }
        //    );
        //

        // PATIENTS
        #region

        context.Patients.AddOrUpdate(i => i.Patient_firstname,
            new PatientModel
            {
                Patient_id = 1,
                Patient_firstname = "John",
                Patient_middlename = "",
                Patient_lastname = "Kelleher",
                Patient_sex = "male",
                Patient_home_number = 090987867,
                Patient_phone_number = 090987867,
                Patient_address_line1 = "14 Steeple View",
                Patient_address_line2 = "Collooney",
                Patient_city = "Sligo",
                Patient_country = "Ireland",
                Patient_dob = Convert.ToDateTime("11/11/1975")
                //Patient_ward_id = 12,
                //Patient_salutation_id = 1
            },
            new PatientModel
            {
                Patient_id = 2,
                Patient_firstname = "Adam",
                Patient_middlename = "",
                Patient_lastname = "Specialero",
                Patient_sex = "male",
                Patient_home_number = 090987867,
                Patient_phone_number = 090987867,
                Patient_address_line1 = "14 Death Street",
                Patient_address_line2 = "Wolf Creek",
                Patient_city = "Dublin",
                Patient_country = "Ireland",
                Patient_dob = Convert.ToDateTime("11/11/1985")
                //Patient_ward_id = 13,
                //Patient_salutation_id = 1
            },
            new PatientModel
            {
                Patient_id = 3,
                Patient_firstname = "Eve",
                Patient_middlename = "Kal",
                Patient_lastname = "Medhare",
                Patient_sex = "female",
                Patient_home_number = 090987867,
                Patient_phone_number = 090987867,
                Patient_address_line1 = "18 Steeple View",
                Patient_address_line2 = "Collooney",
                Patient_city = "Sligo",
                Patient_country = "Ireland",
                Patient_dob = Convert.ToDateTime("11/11/1995")
                //Patient_ward_id = 14,
                //Patient_salutation_id = 1
            },
            new PatientModel
            {
                Patient_id = 4,
                Patient_firstname = "Micheale",
                Patient_middlename = "",
                Patient_lastname = "Rodrigues",
                Patient_sex = "female",
                Patient_home_number = 090987867,
                Patient_phone_number = 090987867,
                Patient_address_line1 = "14 River Walk",
                Patient_address_line2 = "Collooney",
                Patient_city = "Sligo",
                Patient_country = "Ireland",
                Patient_dob = Convert.ToDateTime("11/11/1992")
                //Patient_ward_id = 13,
                //Patient_salutation_id = 1
            },
            new PatientModel
            {
                Patient_id = 5,
                Patient_firstname = "Michalero",
                Patient_middlename = "Do",
                Patient_lastname = "Poncaki",
                Patient_sex = "male",
                Patient_home_number = 090987867,
                Patient_phone_number = 090987867,
                Patient_address_line1 = "17 Steeple View",
                Patient_address_line2 = "Collooney",
                Patient_city = "Sligo",
                Patient_country = "Ireland",
                Patient_dob = Convert.ToDateTime("11/11/1991")
                //Patient_ward_id = 13,
                //Patient_salutation_id = 1
            }
            );

        #endregion

        // DOCTORS
        #region

        context.Doctors.AddOrUpdate(i => i.Doctor_firstname,
            new DoctorModel
            {
                Doctor_id = 1,
                Doctor_username = "michal",
                Doctor_firstname = "Michal",
                Doctor_middlename = "Kel",
                Doctor_lastname = "Poncak",
                Doctor_speciality = "killing",
                Doctor_sex = "male",
                Doctor_home_number = 090987867,
                Doctor_phone_number = 090987867,
                Doctor_address_line1 = "11 Steeple View",
                Doctor_address_line2 = "Collooney",
                Doctor_city = "Sligo",
                Doctor_country = "Ireland",
                Doctor_dob = Convert.ToDateTime("3/4/1991"),
                Doctor_bleep_id = 111
            }
            );

        #endregion

        // NURSES
        #region

        context.Nurses.AddOrUpdate(i => i.Nurse_firstname,
            new NurseModel
            {
                Nurse_id = 1,
                Nurse_username = "lara",
                Nurse_firstname = "Lara",
                Nurse_middlename = "",
                Nurse_lastname = "Croft",
                Nurse_speciality = "Dental",
                Nurse_home_number = 098765432,
                Nurse_phone_number = 098765432,
                Nurse_address_line1 = "11 Steeple View",
                Nurse_address_line2 = "Collooney",
                Nurse_city = "Sligo",
                Nurse_country = "Ireland",
                Nurse_dob = Convert.ToDateTime("11/11/1991")
            }
            //new NurseModel
            //{
            //    Nurse_id = 1,
            //    Nurse_username = "lara",
            //    Nurse_firstname = "Lara",
            //    Nurse_middlename = "",
            //    Nurse_lastname = "Croft",
            //    Nurse_speciality = "Dental",
            //    Nurse_home_number = 098765432,
            //    Nurse_phone_number = 098765432,
            //    Nurse_address_line1 = "11 Steeple View",
            //    Nurse_address_line2 = "Collooney",
            //    Nurse_city = "Sligo",
            //    Nurse_country = "Ireland",
            //    Nurse_dob = Convert.ToDateTime("11/11/1991")
            //}//need more!
            );

        #endregion

        // WARDS
        #region

        context.Wards.AddOrUpdate(i => i.Ward_name,
            new WardModel
            {
                Ward_id = 1,
                Ward_name = "Death Bringer",
                Ward_capacity = 20,
                Ward_manager_id = 1,
                Ward_speciality = "Killing",
                Ward_status = "available",
                Ward_moto = "Masters of the void!"
            }            );

        #endregion

        // EQUIPMENT
        #region

        //context.Equipments.AddOrUpdate(i => i.Equipment_name,
        //    new EquipmentModel
        //    {
        //        Equipment_id = 1,
        //        Equipment_name = "Med Pack",
        //        Equipment_priority_id = 1,
        //        Equipment_quantity = 3,
        //        Equipment_status_id = 1
        //    });

        #endregion

        // SALUTATIONS
        #region

        context.Salutations.AddOrUpdate(i => i.Salutation_name,
            new SalutationModel
            {
                Salutation_id = 1,
                Salutation_name = "Mr"
            },
            new SalutationModel
            {
                Salutation_id = 2,
                Salutation_name = "Mrs"
            },
            new SalutationModel
            {
                Salutation_id = 3,
                Salutation_name = "Ms"
            },
            new SalutationModel
            {
                Salutation_id = 4,
                Salutation_name = "Dr"
            }
            );

        #endregion

        // CARETEAMS
        #region

        context.CareTeams.AddOrUpdate(i => i.Care_team_name,
            new CareTeamModel
            {
                Care_team_id = 1,
                Care_team_name = "Pro Care"
            });

        #endregion
    }











Could you please help find out what i am doing wrong or what am i missing?

Any comments or suggestions are welcome.






Could you please help find out what i am doing wrong or what am i missing?
Any comments or suggestions are welcome.

推荐答案

Here it is, my final suggestion now as answer:



At the end of PatientModel you had:

public SalutationModel Salutation { get;组; }

just add \"virtual\":

public virtual SalutationModel Salutation { get;组; }



The typical convention when you need just a reference to the external entity (1:N): add virtual class to the referring class, and nothing to the referred one.



And the dropdown is also working :)



But you should get rid of table duplication in the database (with and without model in name). And you should consider using c# naming conventions:

- forget PatientModel, just Patient

- if you have a class, you don’’t need to add it’’s name in the property name: not Patient_firstname, just FirstName (CamelCase)

- the properties like name, sex,... are not virtual! Why should they be? virtual properties are for referring other entities or collections of them

- dob?! DateOfBirth :)

- you don’’t need to store the referencing foreign key field in the model, the EF will handle this

- try to separate data model and view model - it is a security risk, because of the model binder



Keep on the good work!
Here it is, my final suggestion now as answer:

At the end of PatientModel you had:
public SalutationModel Salutation { get; set; }
just add "virtual":
public virtual SalutationModel Salutation { get; set; }

The typical convention when you need just a reference to the external entity (1:N): add virtual class to the referring class, and nothing to the referred one.

And the dropdown is also working :)

But you should get rid of table duplication in the database (with and without model in name). And you should consider using c# naming conventions:
- forget PatientModel, just Patient
- if you have a class, you don''t need to add it''s name in the property name: not Patient_firstname, just FirstName (CamelCase)
- the properties like name, sex,... are not virtual! Why should they be? virtual properties are for referring other entities or collections of them
- dob?! DateOfBirth :)
- you don''t need to store the referencing foreign key field in the model, the EF will handle this
- try to separate data model and view model - it is a security risk, because of the model binder

Keep on the good work!


这篇关于MVC3代码优先迁移(表关系不起作用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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