SQLexception: неверное имя столбца (ef dbfirst to codefirst)C#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 SQLexception: неверное имя столбца (ef dbfirst to codefirst)

Сообщение Anonymous »

Я знаю, что на этой теме есть тонна касов, но ни один из ответов, на которые я смотрел, не помог мне. Я уверен, что это что-то простое. Я использовал инструмент «код сначала из базы данных», чтобы произвести классы, но пытаюсь разрешить некоторые ошибки, этот заставляет меня оторвать. ) вовлечены:

Код: Выделить всё

public partial class Contact
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Contact()
{
Contact_Category_Pivot = new HashSet();
}

[Key]
[Column("Contact ID")]
public int Contact_ID { get; set; }

[Column("Contact Name")]
[StringLength(255)]
public string Contact_Name { get; set; }

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

Код: Выделить всё

public partial class Contact_Category
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Contact_Category()
{
Contact_Category_Pivot = new HashSet();
}

[Key]
public Guid Contact_Category_ID { get; set; }

[Required]
[StringLength(50)]
public string Contact_Category_Name { get; set; }

[Required]
[StringLength(100)]
public string Contact_Category_Description { get; set; }

public int Sequence { get; set; }

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

Код: Выделить всё

public partial class Contact_Category_Pivot
{
[Column("ID")]
[Key]
public Guid PivotID { get; set; }
[Column("Contact_ID")]
public int Contact_ID { get; set; }

public Guid Contact_Category_ID { get; set; }

public Contact Contact { get; set; }

public Contact_Category Contact_Category { get; set; }
}
< /code>
OnModelCreating
Метод:

Код: Выделить всё

modelBuilder.Entity()
.HasMany(e => e.Contact_Category_Pivot)
.WithRequired(e => e.Contact)
.HasForeignKey(e => e.Contact_ID);

modelBuilder.Entity()
.HasMany(e => e.Contact_Category_Pivot)
.WithRequired(e => e.Contact_Category)
.WillCascadeOnDelete(false);
< /code>
In case it is unclear; the pivot table holds a key from each other table plus an ID per record (RecordID, ContactID, ContactCategoryID
).
Если я пропустил какие -либо необходимые образцы, дайте мне знать.
Ошибка возникает при попытке найти «Контактная категория» с использованием категории , полученной из таблицы Pivot (для целей устранения неполадок я здесь жестко кодировал идентификатор):
Contact_Category CG = db.Contact_Category.Find(new Guid("a2ab17df-5a15-4b38-aa5f-4577653a1ec9"));
< /code>
On that line, I get an error

Invalid column name error on Contact_Contact_ID

I know the problem is related to the foreign key relationship, I'm just not sure what I need to do to resolve it.
I've tried various changes based on answers I've seen but each seems to create a new problem, so I've had to resort to requesting assistance from all you wonderful folk! Hopefully someone spots something obvious to those more experienced with code-first EF!
Note: I believe the supplied samples are all auto-generated but it is possible changes from my tinkering have slipped in
Bonus: once I have this sorted, I need to figure out how to do the initial-migration step accounting for these changes, so if anyone can point me in the right direction for that if its likely to be an issue, that would also be appreciated
EDIT
Contact has several other relations not defined above. If I load a record which uses ONLY a contact record it works, but as soon as I try to access any relation - even indirect relations like that Contact_Category table (which is linked via the pivot table), I receive the error.
Answering comments: all the properties of Contact_Categories & Contact_Category_Pivot are included above, I've only removed extra properties from Contact because it has a ton of columns.

Подробнее здесь: https://stackoverflow.com/questions/794 ... -codefirst
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • SQLexception: неверное имя столбца (ef dbfirst to codefirst)
    Anonymous » » в форуме C#
    0 Ответы
    7 Просмотры
    Последнее сообщение Anonymous
  • SQLexception: неверное имя столбца (ef dbfirst to codefirst)
    Anonymous » » в форуме C#
    0 Ответы
    10 Просмотры
    Последнее сообщение Anonymous
  • Проблема с JpaRepository – SQLException: неверное имя столбца
    Anonymous » » в форуме JAVA
    0 Ответы
    10 Просмотры
    Последнее сообщение Anonymous
  • System.data.sqlclient.sqlexception: неверное имя столбца 'phone_types_phone_type_id'
    Anonymous » » в форуме C#
    0 Ответы
    3 Просмотры
    Последнее сообщение Anonymous
  • Java.sql.SQLException: запрошено неверное преобразование
    Anonymous » » в форуме JAVA
    0 Ответы
    27 Просмотры
    Последнее сообщение Anonymous

Вернуться в «C#»