SqlException: неверное имя столбца для строки, которая не существует в решении - PullRequest
0 голосов
/ 10 октября 2018

Я пытаюсь заставить Entity Framework работать с созданной базой данных, и я получаю странную ошибку, которая не имеет смысла для меня.

Когда я пытаюсь запустить мою программуЯ получаю исключение со следующей трассировкой стека:

Unhandled Exception: System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. 
See the inner exception for details. ---> System.Data.SqlClient.SqlException: Invalid column name 'CorrespondenceAddress_AddressId'.

Программа звучит так, будто пытается найти столбец CorrespondenceAddress_AddressId, и выдает исключение, когда не может его найти.Однако этот столбец не был определен нигде в моей базе данных или в моем коде в моем решении, поэтому я не понимаю, откуда он получает имя этого столбца.

Класс, о котором идет речь, имеет CorrespondenceAddressмой класс Property.Как определено ниже:

public partial class Property
    {
        private int _propertyId;
        private int _instructionId;
        private int _referenceNumber;
        private string _caseOwner;
        private int _amountBorrowed;
        private Address _securityAddress;
        private int _correspondenceAddressId;
        private int _securityAddressId;

        public Property()
        {
            Occupiers = new HashSet<Occupier>();
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Property(int propertyId, int instructionId, int reference, int amountBorrowed, JurisdictionTypes jurisdiction, FunderTypes funder,
                                bool correspondenceAddressIsSecurityAddress, Address correspondenceAddress, Address securityAddress)
        {
            Occupiers = new HashSet<Occupier>();

            PropertyId = propertyId;
            InstructionId = instructionId;
            ReferenceNumber = reference;
            CaseOwner = "";
            AmountBorrowed = amountBorrowed;
            Jurisdiction = jurisdiction;
            Funder = funder;
            CorrespondenceAddressIsSecurityAddress = correspondenceAddressIsSecurityAddress;
            SecurityAddress = securityAddress;
        }

        [Key]
        public int PropertyId
        {
            get => this._propertyId;
            set => this._propertyId = Math.Abs(value);
        }

        public int InstructionId
        {
            get => this._instructionId;
            set => this._instructionId = Math.Abs(value);
        }

        public int CorrespondenceAddressId
        {
            get => this._correspondenceAddressId;
            set => this._correspondenceAddressId = Math.Abs(value);
        }

        public int SecurityAddressId
        {
            get => this._securityAddressId;
            set => this._securityAddressId = Math.Abs(value);
        }

        public int ReferenceNumber
        {
            get => this._referenceNumber;
            set => this._referenceNumber = Math.Abs(value);
        }

        [StringLength(3)]
        public string CaseOwner
        {
            get => this._caseOwner;
            set => this._caseOwner = value.Trim();
        }

        public int AmountBorrowed
        {
            get => this._amountBorrowed;
            set => this._amountBorrowed = Math.Abs(value);
        }

        public TenureTypes Tenure { get; set; }

        public JurisdictionTypes Jurisdiction { get; set; }

        public FunderTypes Funder { get; set; }

        public bool CorrespondenceAddressIsSecurityAddress { get; set; }

        public virtual Address CorrespondenceAddress { get; set; }

        public virtual Address SecurityAddress
        {
            get => _securityAddress;
            set => _securityAddress = CorrespondenceAddressIsSecurityAddress ? null : value;
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Occupier> Occupiers { get; set; }

        public virtual SolicitorInstruction SolicitorInstruction { get; set; }
    }

Таблица базы данных, которая соответствует этому классу, была создана с использованием следующего запроса:

CREATE TABLE Property
(
    PropertyId INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
    InstructionId INT NOT NULL FOREIGN KEY REFERENCES SolicitorInstruction(InstructionId),
    CorrespondenceAddressId INT NOT NULL FOREIGN KEY REFERENCES SolicitorInstruction(InstructionId),
    SecurityAddressId INT NOT NULL FOREIGN KEY REFERENCES SolicitorInstruction(InstructionId),

    ReferenceNumber INT NOT NULL,
    CaseOwner VARCHAR(3),
    AmountBorrowed INT,

    --2 tenure types: 1 = Freehold and 2 = Leasehold
    Tenure INT,

    --1 for Scotland, 2 for E&W, 3 for NI
    Jurisdiction INT,

    --5 funder types: Standard, PIC, LT, JR, Partnership
    Funder INT,

    CorrespondenceAddressIsSecurityAddress BIT NOT NULL,

    CONSTRAINT CHK_Tenure CHECK (Tenure BETWEEN 1 AND 2),
    CONSTRAINT CHK_Jurisdiction CHECK (Jurisdiction BETWEEN 1 AND 3),
    CONSTRAINT CHK_Funder CHECK (Funder BETWEEN 1 AND 5),
)

Может кто-нибудь объяснить эту ошибку для меня, так как я не уверенкак это исправить.

1 Ответ

0 голосов
/ 10 октября 2018

Измените порядок CorrespondenceAddressId и SecurityAddressId как в вашем классе сущности, так и в таблице.Меняется ли теперь сообщение об ошибке на SecurityAddress_AddressId?

EF выводит вещи с поведением по умолчанию, когда вещи неявно объявляются.CorrespondenceAddress_AddressId - это попытка найти то, что не объявлено.

Вы декларируете только одно:

SolicitorInstruction SolicitorInstruction { get; set; }

Но есть 3 FK для SolicitorInstruction.Ef может заставить первого работать на InstructionId и угадывать другие.

У вас есть код решения здесь:

https://stackoverflow.com/a/5559300/10192838

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...