【问题标题】:how to initiate a foreign key when you add a new record?添加新记录时如何启动外键?
【发布时间】:2015-06-12 15:36:39
【问题描述】:

我有一个小问题。我想测试两个表的连接。

public class Patient:Person
{
    //inheritance ID
    public string insuranceNumber { get; set; }

    public virtual PatientCard patientCard {get; set;}

}

public class PatientCard
    {

        public PatientCard()
        {
            this.patient = new HashSet<Patient>();
            this.visit = new HashSet<Visit>();
        }

        public long id { get; set; }
        public string bloodType { get; set; }
        public string creationDate { get; set; }

        public virtual ICollection<Patient> patient { get; set; }
        public virtual ICollection<Visit> visit { get; set; }
    }

添加新记录时如何启动外键? 我的尝试看起来像这样......

                var patient = new Patient { 
                    ID=1, name = "Alicja", lastname = "Nowacka", 
                    pesel = "89192232", address = "Szczecin", 
                    phoneNumber = "11233332", insuranceNumber = "3211233123" 
                };
                db.Persons.Add(patient);
                db.SaveChanges();


                var patientCard = new PatientCard { 
                    bloodType = "A", creationDate = "2014-06-16", 
                    patient= //**a reference to the key**
                };

谢谢!

【问题讨论】:

    标签: c# mysql entity-framework-6


    【解决方案1】:

    你的外键引用是什么?病人身份证? 如果 ID 是身份,您只需要在 db.SaveChanges(); 之后获取 patient.Id

    【讨论】:

    • 是的,我的外键是ID,我尝试直接启动耐心=1,但是我得到一个错误“无法将类型'int'隐式转换为'System.Collections.Generic.ICollection"
    • 你应该试试这个方法:patientCard.patient.add(patient)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    • 1970-01-01
    • 2018-02-17
    • 1970-01-01
    相关资源
    最近更新 更多