Using system data entity ошибка

I’m using WS class and it gave me error when I run the application:

The type or namespace name 'Entity' does not exist in the namespace 'System.Data' 

I have a reference to the System.Data; and to System.Data.Entity;
But no changes. I keep getting the error. I have also in the web.config the line:

<compilation debug ="true" targetFramework="4.0"/>

halfer's user avatar

halfer

19.9k17 gold badges100 silver badges187 bronze badges

asked Apr 2, 2012 at 7:30

st mnmn's user avatar

6

Right-click on the Solution from the Visual Studio Solution Explorer click the Manage Nuget packages for solution and install the EntityFramework

answered Aug 4, 2014 at 18:06

Tony Ding's user avatar

Tony DingTony Ding

1,1412 gold badges7 silver badges2 bronze badges

5

Hi this post is very misleading, if your reading this 2 years on.

With using EF6 and .net 4.5.1 in VS 2013 I have had to reference the following to get this to work

using System.Data.Entity.Core.EntityClient;

a little different to before,

this is more of a FYI for people that come here for help on newer problems than a answer to the original question

answered Jul 8, 2014 at 9:12

AlanMorton2.0's user avatar

AlanMorton2.0AlanMorton2.0

1,0432 gold badges12 silver badges22 bronze badges

2

Thanks every body!
I found the solution. not that I understand why but I tried this and it worked!
I just had to add a reference to: System.Data.Entity.Design
and don’t have to write any using in the code.
Thanks!

answered Apr 2, 2012 at 9:43

st mnmn's user avatar

st mnmnst mnmn

3,5653 gold badges25 silver badges32 bronze badges

2

I had entity framework 6.1.3, upgraded (well, more downgraded in NuGet) to 6.1.2. Worked.

answered Apr 17, 2016 at 13:59

TJPrgmr's user avatar

TJPrgmrTJPrgmr

1411 silver badge3 bronze badges

1

Most of the answers here seem to lack awareness of the namespace change that happened between EF 6.2 and 6.3.

I was intentionally upgrading from EF 6.1 to 6.3 to be able to target .NET Standard 2.1. However, I accidentally used .NET Standard 2.0 for the new target in my lib and then got the The type or namespace name 'Entity' does not exist in the namespace 'System.Data'. This GH issue comment gave me the clue I needed to fix. I changed my lib target to .NET Standard 2.1 and the project compiled. No re-installs, uninstalls, or restarts were required.

answered May 15, 2020 at 23:45

gabe's user avatar

gabegabe

1,8732 gold badges20 silver badges36 bronze badges

You need to install Entity framework by right click on your VS solution and click Manage NuGet Package solution and search there Entity framework.
After installation the issue will be solved

answered Nov 3, 2016 at 6:10

Rajesh Kumar Swain's user avatar

I just had the same error with Visual Studio 2013 and EF6. I had to use a NewGet packed Entity Framework and done the job perfectly

answered Mar 8, 2015 at 18:18

Cormac Hallinan's user avatar

I will add my answer to cover all cases:

My solution was unistalling EntityFramework from NuGet Package Manager and then I was prompted to restart Visual Studio because it couldn’t «finalize the uninstall».

I restarted Visual Studio and reinstalled EntityFramework then my problem was solved.

Hope this helps someone!

answered May 5, 2016 at 13:25

GigiSan's user avatar

GigiSanGigiSan

1,1702 gold badges19 silver badges30 bronze badges

1

Make sure you have the EntityFramework Nuget package installed for your project.

From @TonyDing’s answer:

Right-click on the Solution from the Visual Studio Solution Explorer
click the Manage Nuget packages for solution and install the
EntityFramework

Once it is installed, I still had the error, but then did a reinstall per @papergodzilla’s comment:

Update-Package -reinstall

and it resolved my issue

Do this in the Package Manager Console (View > Other windows > Package Manager Console).
Now everything is good!

toha's user avatar

toha

5,1014 gold badges40 silver badges52 bronze badges

answered Sep 10, 2018 at 12:19

Protector one's user avatar

Protector oneProtector one

6,9365 gold badges62 silver badges86 bronze badges

1

I installed EntityFramework 6.2 instead of 6.3 and it worked.

Perhaps it is the .NetCoreApp v2.1 or .NETFramework v4.6.1.

Pingolin's user avatar

Pingolin

3,1616 gold badges25 silver badges40 bronze badges

answered Nov 26, 2019 at 19:21

Doug Moore's user avatar

1

My solution was simple! I was actually having this error when checked out a repo from a svn server. I took following steps to remove error

  1. Cleaned solution
  2. Went to nuget package manager and uninstalled the entity framework.
  3. Removed DataModel and its .cs components.
  4. Shutdown the VS and opened again.
  5. Installed Entity Framework and Recreated entity model.
  6. Check if there is any files needed «Include in the solution».
    It worked like a charm

answered Sep 28, 2018 at 5:02

Ansar Nisar's user avatar

tried reinstall — no luck. i had to refresh a table in my model before it would find Entity.

answered Mar 4, 2016 at 12:49

Joe's user avatar

JoeJoe

1,64912 silver badges10 bronze badges

It’s helped me, I uninstalled EF, restarted VS and I added ‘using’:

using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;

answered May 19, 2017 at 14:22

Roberto Gata's user avatar

I had to refresh my DBModel. That solved it

answered Jul 25, 2017 at 9:25

Dare's user avatar

DareDare

313 bronze badges

I had to reference System.Data.DataSetExtensions, which seems completely illogical

answered Aug 17, 2017 at 9:51

Erik Bergstedt's user avatar

I found the root cause is when you install the nuget packages through the UI the scripts won’t run sometimes. So I’d recommend open Output view while you do that. If you don’t see the license agreement window when installing Nuget, there is a better change your IDE isn’t doing the job right. So that’s why a restart, cleanup and rebuild helps!

PS: That adding anything under System.Data.Entity.* helps because, that triggers the Nuget installer to work properly. But this I found a quite unreliable way.

So just watch the output window, you MUST see something like a successful nuget installation message at the end. Most the time when there an issue, Nuget installer won’t even kick off. That’s when your restart of IDE is going to help.

When things go well, Nuget package manager and IDE (I used Installer term above) would do the change, compile the solution and keep you happy! But when its not give a little help by restarting IDE and watching that Output window!

answered May 24, 2019 at 4:36

SydMK's user avatar

SydMKSydMK

4354 silver badges12 bronze badges

If you are using EF version more than 6.x , then see if you have installed the entity framework nuget package in every project of your solution. You might have installed Ef but not in that particular project which you are working on.

answered Oct 13, 2019 at 13:35

user12209639's user avatar

I had the same errors.

I added System.Data.Entity.Repository from Nuget Packages and the errors disappears.

Hope it wil help!

answered Aug 28, 2018 at 14:38

FAHA's user avatar

I noticed that in the csproj the framework entity had hintpath like

<HintPath>..\..\..\..\..\..\Users\{myusername}

I had this in the nuget.config file:

 <config>
 <add key="repositoryPath" value="../lib" />
 </config>

a) I removed the above lines, b) uninstalled the framework entity package, c) THEN CLOSED THE solution and reopened it, d) reinstalled the framework.

It fixed my issue.

answered Sep 11, 2018 at 15:11

Antonin GAVREL's user avatar

Antonin GAVRELAntonin GAVREL

9,7569 gold badges54 silver badges81 bronze badges

If you’re using a database-first approach:

Before uninstalling / reinstalling Entity Framework, first try simply adding another table / stored procedure to your model (assuming there are any currently unmapped). That fixed the issue for me. Of course if you don’t need the resource mapped then just delete it from the model afterwards. But it looks like a force-regeneration of the edmx did the trick.

answered Feb 26, 2019 at 22:59

Jason Sultana's user avatar

Jason SultanaJason Sultana

1,0492 gold badges10 silver badges10 bronze badges

For those using vscode make sure that EntityFramework is installed by checking your app.csproj file and weirdly enough check if your file where you’re referencing to System.Data.Entity is in the /obj folder.

answered May 20, 2021 at 13:05

samuel gast's user avatar

samuel gastsamuel gast

3314 silver badges17 bronze badges

I had just updated my Entity framework to version 6 in my Visual studio 2013 through NugetPackage and add following References:

System.Data.Entity,
System.Data.Entity.Design,
System.Data.Linq

by right clicking on references->Add references in my project.
Now delete my previously created Entity model and recreate it again,Built solution. Now It works fine for me.

demonplus's user avatar

demonplus

5,62312 gold badges49 silver badges68 bronze badges

answered Sep 8, 2015 at 7:23

Bikash Kumar's user avatar

I’m using WS class and it gave me error when I run the application:

The type or namespace name 'Entity' does not exist in the namespace 'System.Data' 

I have a reference to the System.Data; and to System.Data.Entity;
But no changes. I keep getting the error. I have also in the web.config the line:

<compilation debug ="true" targetFramework="4.0"/>

halfer's user avatar

halfer

19.9k17 gold badges100 silver badges187 bronze badges

asked Apr 2, 2012 at 7:30

st mnmn's user avatar

6

Right-click on the Solution from the Visual Studio Solution Explorer click the Manage Nuget packages for solution and install the EntityFramework

answered Aug 4, 2014 at 18:06

Tony Ding's user avatar

Tony DingTony Ding

1,1412 gold badges7 silver badges2 bronze badges

5

Hi this post is very misleading, if your reading this 2 years on.

With using EF6 and .net 4.5.1 in VS 2013 I have had to reference the following to get this to work

using System.Data.Entity.Core.EntityClient;

a little different to before,

this is more of a FYI for people that come here for help on newer problems than a answer to the original question

answered Jul 8, 2014 at 9:12

AlanMorton2.0's user avatar

AlanMorton2.0AlanMorton2.0

1,0432 gold badges12 silver badges22 bronze badges

2

Thanks every body!
I found the solution. not that I understand why but I tried this and it worked!
I just had to add a reference to: System.Data.Entity.Design
and don’t have to write any using in the code.
Thanks!

answered Apr 2, 2012 at 9:43

st mnmn's user avatar

st mnmnst mnmn

3,5653 gold badges25 silver badges32 bronze badges

2

I had entity framework 6.1.3, upgraded (well, more downgraded in NuGet) to 6.1.2. Worked.

answered Apr 17, 2016 at 13:59

TJPrgmr's user avatar

TJPrgmrTJPrgmr

1411 silver badge3 bronze badges

1

Most of the answers here seem to lack awareness of the namespace change that happened between EF 6.2 and 6.3.

I was intentionally upgrading from EF 6.1 to 6.3 to be able to target .NET Standard 2.1. However, I accidentally used .NET Standard 2.0 for the new target in my lib and then got the The type or namespace name 'Entity' does not exist in the namespace 'System.Data'. This GH issue comment gave me the clue I needed to fix. I changed my lib target to .NET Standard 2.1 and the project compiled. No re-installs, uninstalls, or restarts were required.

answered May 15, 2020 at 23:45

gabe's user avatar

gabegabe

1,8732 gold badges20 silver badges36 bronze badges

You need to install Entity framework by right click on your VS solution and click Manage NuGet Package solution and search there Entity framework.
After installation the issue will be solved

answered Nov 3, 2016 at 6:10

Rajesh Kumar Swain's user avatar

I just had the same error with Visual Studio 2013 and EF6. I had to use a NewGet packed Entity Framework and done the job perfectly

answered Mar 8, 2015 at 18:18

Cormac Hallinan's user avatar

I will add my answer to cover all cases:

My solution was unistalling EntityFramework from NuGet Package Manager and then I was prompted to restart Visual Studio because it couldn’t «finalize the uninstall».

I restarted Visual Studio and reinstalled EntityFramework then my problem was solved.

Hope this helps someone!

answered May 5, 2016 at 13:25

GigiSan's user avatar

GigiSanGigiSan

1,1702 gold badges19 silver badges30 bronze badges

1

Make sure you have the EntityFramework Nuget package installed for your project.

From @TonyDing’s answer:

Right-click on the Solution from the Visual Studio Solution Explorer
click the Manage Nuget packages for solution and install the
EntityFramework

Once it is installed, I still had the error, but then did a reinstall per @papergodzilla’s comment:

Update-Package -reinstall

and it resolved my issue

Do this in the Package Manager Console (View > Other windows > Package Manager Console).
Now everything is good!

toha's user avatar

toha

5,1014 gold badges40 silver badges52 bronze badges

answered Sep 10, 2018 at 12:19

Protector one's user avatar

Protector oneProtector one

6,9365 gold badges62 silver badges86 bronze badges

1

I installed EntityFramework 6.2 instead of 6.3 and it worked.

Perhaps it is the .NetCoreApp v2.1 or .NETFramework v4.6.1.

Pingolin's user avatar

Pingolin

3,1616 gold badges25 silver badges40 bronze badges

answered Nov 26, 2019 at 19:21

Doug Moore's user avatar

1

My solution was simple! I was actually having this error when checked out a repo from a svn server. I took following steps to remove error

  1. Cleaned solution
  2. Went to nuget package manager and uninstalled the entity framework.
  3. Removed DataModel and its .cs components.
  4. Shutdown the VS and opened again.
  5. Installed Entity Framework and Recreated entity model.
  6. Check if there is any files needed «Include in the solution».
    It worked like a charm

answered Sep 28, 2018 at 5:02

Ansar Nisar's user avatar

tried reinstall — no luck. i had to refresh a table in my model before it would find Entity.

answered Mar 4, 2016 at 12:49

Joe's user avatar

JoeJoe

1,64912 silver badges10 bronze badges

It’s helped me, I uninstalled EF, restarted VS and I added ‘using’:

using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;

answered May 19, 2017 at 14:22

Roberto Gata's user avatar

I had to refresh my DBModel. That solved it

answered Jul 25, 2017 at 9:25

Dare's user avatar

DareDare

313 bronze badges

I had to reference System.Data.DataSetExtensions, which seems completely illogical

answered Aug 17, 2017 at 9:51

Erik Bergstedt's user avatar

I found the root cause is when you install the nuget packages through the UI the scripts won’t run sometimes. So I’d recommend open Output view while you do that. If you don’t see the license agreement window when installing Nuget, there is a better change your IDE isn’t doing the job right. So that’s why a restart, cleanup and rebuild helps!

PS: That adding anything under System.Data.Entity.* helps because, that triggers the Nuget installer to work properly. But this I found a quite unreliable way.

So just watch the output window, you MUST see something like a successful nuget installation message at the end. Most the time when there an issue, Nuget installer won’t even kick off. That’s when your restart of IDE is going to help.

When things go well, Nuget package manager and IDE (I used Installer term above) would do the change, compile the solution and keep you happy! But when its not give a little help by restarting IDE and watching that Output window!

answered May 24, 2019 at 4:36

SydMK's user avatar

SydMKSydMK

4354 silver badges12 bronze badges

If you are using EF version more than 6.x , then see if you have installed the entity framework nuget package in every project of your solution. You might have installed Ef but not in that particular project which you are working on.

answered Oct 13, 2019 at 13:35

user12209639's user avatar

I had the same errors.

I added System.Data.Entity.Repository from Nuget Packages and the errors disappears.

Hope it wil help!

answered Aug 28, 2018 at 14:38

FAHA's user avatar

I noticed that in the csproj the framework entity had hintpath like

<HintPath>..\..\..\..\..\..\Users\{myusername}

I had this in the nuget.config file:

 <config>
 <add key="repositoryPath" value="../lib" />
 </config>

a) I removed the above lines, b) uninstalled the framework entity package, c) THEN CLOSED THE solution and reopened it, d) reinstalled the framework.

It fixed my issue.

answered Sep 11, 2018 at 15:11

Antonin GAVREL's user avatar

Antonin GAVRELAntonin GAVREL

9,7569 gold badges54 silver badges81 bronze badges

If you’re using a database-first approach:

Before uninstalling / reinstalling Entity Framework, first try simply adding another table / stored procedure to your model (assuming there are any currently unmapped). That fixed the issue for me. Of course if you don’t need the resource mapped then just delete it from the model afterwards. But it looks like a force-regeneration of the edmx did the trick.

answered Feb 26, 2019 at 22:59

Jason Sultana's user avatar

Jason SultanaJason Sultana

1,0492 gold badges10 silver badges10 bronze badges

For those using vscode make sure that EntityFramework is installed by checking your app.csproj file and weirdly enough check if your file where you’re referencing to System.Data.Entity is in the /obj folder.

answered May 20, 2021 at 13:05

samuel gast's user avatar

samuel gastsamuel gast

3314 silver badges17 bronze badges

I had just updated my Entity framework to version 6 in my Visual studio 2013 through NugetPackage and add following References:

System.Data.Entity,
System.Data.Entity.Design,
System.Data.Linq

by right clicking on references->Add references in my project.
Now delete my previously created Entity model and recreate it again,Built solution. Now It works fine for me.

demonplus's user avatar

demonplus

5,62312 gold badges49 silver badges68 bronze badges

answered Sep 8, 2015 at 7:23

Bikash Kumar's user avatar

12 ответов

Спасибо каждому телу!
Я нашел решение. не то, что я понимаю, почему, но я пробовал это, и это сработало!
Мне просто нужно было добавить ссылку на: System.Data.Entity.Design
и не нужно писать код using в коде.
Спасибо!

st mnmn

Поделиться

Щелкните правой кнопкой мыши по Solution из Visual Studio Solution Explorer, выберите «Управление пакетами Nuget» для решения и установите EntityFramework

Tony Ding

Поделиться

Привет, этот пост очень вводит в заблуждение, если вы читаете эти 2 года.

С использованием EF6 и .net 4.5.1 в VS 2013 я должен был ссылаться на следующее, чтобы заставить это работать

using System.Data.Entity.Core.EntityClient;

немного отличается от предыдущего,

Это больше похоже на FYI для людей, которые приходят сюда для помощи в решении новых проблем, чем ответ на исходный вопрос.

AlanMorton2.0

Поделиться

Вам необходимо установить инфраструктуру Entity, щелкнув правой кнопкой мыши на вашем VS-решении и выберите «Управление пакетом решений NuGet» и найдите там инфраструктуру Entity.
После установки проблема будет решена.

Rajesh Kumar Swain

Поделиться

У меня была структура фреймворка 6.1.3, обновленная (ну, еще более пониженная в NuGet) до 6.1.2. Работали.

TJPrgmr

Поделиться

У меня была такая же ошибка с Visual Studio 2013 и EF6. Мне пришлось использовать упакованную платформу Entity Framework NewGet и отлично выполнять работу

Cormac Hallinan

Поделиться

Я добавлю свой ответ, чтобы охватить все случаи:

Мое решение было unistalling EntityFramework из NuGet Package Manager, а затем мне было предложено перезапустить Visual Studio, потому что он не смог «завершить удаление».

Я перезапустил Visual Studio и переустановил EntityFramework, после чего моя проблема была решена.

Надеюсь, это поможет кому-то!

GigiSan

Поделиться

Мне пришлось ссылаться на System.Data.DataSetExtensions, который кажется совершенно нелогичным

Erik Bergstedt

Поделиться

Мне пришлось обновить мой DBModel. Это решило его

Dare

Поделиться

Это помогло мне, я удалил EF, перезапустил VS и добавил «using»:

using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;

Roberto Gata

Поделиться

попробовал переустановить — не повезло. Мне пришлось обновить таблицу в моей модели, прежде чем она найдет Entity.

Joe

Поделиться

Я только что обновил мою инфраструктуру Entity до версии 6 в своей Visual Studio 2013 через NugetPackage и добавлю следующие ссылки:

System.Data.Entity,
System.Data.Entity.Design,
System.Data.Linq

щелкнув правой кнопкой мыши по ссылкам- > Добавить ссылки в моем проекте.
Теперь удалите мою ранее созданную модель Entity и снова создайте ее, встроенное решение. Теперь он отлично работает для меня.

Bikash Kumar

Поделиться

Ещё вопросы

  • 1Линия между двумя перетаскиваемыми точками на холсте matplotlib pyqt5
  • 1Вычисление косинусного сходства между двумя тензорами в Керасе
  • 1Проблема оптимизации колонии муравьев
  • 0AngularJS: вложенные директивы — передача данных не работает
  • 0JQuery обход и поиск текстовых полей
  • 0навигатор настроен на полный диапазон
  • 1Как получить токен на предъявителя из заголовка авторизации в Javascript (Angular2 / 4)?
  • 0Тестирование углового модала открытое обещание
  • 0Как привязать ответные данные из моего пост-метода контроллера в MVC
  • 1Конкретная строка данных в Pandas кажется индексной
  • 1Как отловить ошибку HTTP по java.net.URL
  • 1Развертывание таблиц базы данных в порядке взаимосвязи с ограничениями
  • 1Будет ли запускать отдельный поток, который использует метод из основного потока, по-прежнему запускать его в основном потоке? (С #)
  • 1Один однократный фильтр для всех запросов ко всем сервлетам
  • 0STL — добавление значений к вектору, хранящемуся в карте STL
  • 0AngularJS 10 $ digest () достигнуты итерации. Попытка синхронизировать службу, контроллер и представление с помощью $ watch работает, но вызывает ошибки
  • 0JQuery Dropdown с помощью JQuery Dummy
  • 0Значение формы не передается в angularjs
  • 0Некоторая довольно сложная тригонометрия для изменения размеров окна
  • 1Правила безопасности Firestore request.query.orderBy не работает
  • 1Использует ли эта реализация сортировки слиянием взаимную рекурсию?
  • 0Почему статическая переменная класса не может быть размещена в стеке?
  • 1Передача аргументов во фрагменте
  • 1Уведомления не получаются на устройство, но получают успех на FCM, в чем проблема?
  • 1Размер бита System.ConsoleColor
  • 1Отправить электронную почту через Python с помощью Outlook 2016, не открывая его
  • 1Значение не печатать
  • 1Ошибка в библиотеке, созданной с помощью jitpack: невозможно разрешить зависимость для ‘: app @ debug / compileClasspath’
  • 0setAttribute не работает
  • 0Калькулятор чаевых с Jquery
  • 1Рассчитайте время в пути между двумя точками (координатами), используя Google Maps API
  • 1Python Threading. Почему потоки блокируют друг друга? [Дубликат]
  • 0Как сгенерировать серийный номер при выборе всех данных из таблицы?
  • 2Я получаю утечку памяти, когда начинаю переход с общими элементами из элемента утилизатора
  • 1Использование Unicode в пункте меню google-apps
  • 1C # Формат даты {0: t} — {0: t + 1} 00:00 — 01:00
  • 0Как связать статическую библиотеку C ++ с PHP?
  • 0Sql запрос Join / Где 3 таблицы
  • 1Метеор выполняет функции синхронно
  • 1LINQ Выберите заявление. Анонимный метод возвращает исключение
  • 1Как изменить ширину полосы прокрутки в WPF?
  • 1Местоположение включено, но слушатель ничего не возвращает
  • 0jQuery — добавление CSS3-анимации в div с использованием jQuery.
  • 1Отправить письмо без аутентификации
  • 0Горизонтальная страница контента Windows 8
  • 0функция select () во вкладках — Angular Bootstrap
  • 0Загрузить всплывающее окно jQuery при загрузке страницы, используя данные URL?
  • 1Canvas неправильно рисует край при извлечении изображения из спрайта
  • 1загрузить больше данных на страницу прокрутки
  • 1Добавление слушателей в Amcharts с Angular4 [дубликаты]

0 / 0 / 0

Регистрация: 05.09.2013

Сообщений: 5

1

05.09.2013, 10:29. Показов 14771. Ответов 3


Студворк — интернет-сервис помощи студентам

Здравствуйте. Есть задача такой сложности. Я пишу сайт на MVC 4. И нужно при подключении к базе данных использовать Entity Framework, а именно я не могу подключить пространство имён
using System.Data.Entity и не знаю как это сделать.

Нужно подключить в проект пространство имен using System.Data.Entity

П.С Стоит Visual Studio 2012 Ultimate + Обновление 3 для Visual Studio
Net Framework 4.5 + ADO.NET Entity Framework 4.1

Спасибо. Благодарен за любой дельный совет.

Миниатюры

Entity Framework не подключается пространство имен
 



0



Сергей 83

98 / 96 / 15

Регистрация: 28.03.2011

Сообщений: 565

05.09.2013, 12:10

2

вот автоматически созданный класс ентити использует:

C#
1
2
3
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;

в Refrences вижу есть ссылки на пространства имен:
System.Data, System.Data.Entity и др…

— это идет по умолчанию в проекте mvc4, если я не ошибаюсь.

может поможет добавить вручную: http://stackoverflow.com/quest… ata-entity



1



7 / 7 / 1

Регистрация: 09.03.2011

Сообщений: 116

05.09.2013, 12:14

3

На скрине не видно добавлена ли ссылка на библиотеку Entity Framework, если нет то проблема в этом. В обозревателе решений на пункте Reference клик правой — добавить ссылку- и выбрать Entity Framework



2



69 / 69 / 12

Регистрация: 09.08.2011

Сообщений: 116

Записей в блоге: 1

05.09.2013, 23:50

4

Если не получилось, можно сделать так.

1.Вызвать NuGet

Entity Framework не подключается пространство имен

2.Указать в старке поиска EntityFramework и установить

Entity Framework не подключается пространство имен

3.Прописать using System.Data.Entity;

Entity Framework не подключается пространство имен



2



  • Remove From My Forums
  • Question

  • I’m having trouble getting to first base with the Entity Framework. Below is my sample code, with errors noted as comments at the applicable spot. What am I missing?

    It is run with this code.

    DoStuff d = new DoStuff();
    d.Test();

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.Entity;

    namespace EFTest {
        class Misc : DbContext {
            //If constructor not commentd out compile error
            //error = Error 1 The type ‘System.Data.Objects.ObjectContext’ is defined in an assembly that is not referenced. You must add a reference to assembly ‘System.Data.Entity,
    Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089′. D:\F\Code\Misc\db\EntityFramework\EFTest\EFTest\Misc.cs 12 16 EFTest
            //yet as seen above System.Data.Entity is referenced and
            //Project references includes reference to Entity Framework
    4.1
            //But the metadata for DBContext file of the framework has these lines which show both 4.0 and 4.1
            //#region Assembly EntityFramework.dll,
    v4.0.30319
            //// C:\Program Files (x86)\Microsoft ADO.NET Entity
    Framework 4.1\Binaries\EntityFramework.dll
            //#endregion
            //public Misc()
            //    : base(«MyCon») {//my connection string in the app config. it works fine elsewhere
            //}

            public DbSet<Father> Fathers { get; set; }
            public DbSet<Son> Sons { get; set; }
        }
        class Father {
            public long Id { get; set; }
            public string Name { get; set; }
            public List<Son> Sons { get; set; }
        }
        class Son {
            public long Id { get; set; }
            public string Name { get; set; }
            public long FatherId { get; set; }
        }
        class DoStuff {
            Misc db = new Misc();
            //this line will not compile at all if uncommented
            //Error 1 Invalid token ‘(‘ in class, struct, or interface member declaration D:\F\Code\Misc\db\EntityFramework\EFTest\EFTest\Misc.cs 38 32 EFTest
            //Database.SetInitializer(new DropCreateDatabaseIfModelChanges<Misc>());

            public void Test() {
                try {
                    //if constructor is commented out
                    //Error here  = «CREATE DATABASE permission denied in database ‘master’.»
                    Father f = db.Fathers.FirstOrDefault();
                    Son s = db.Sons.FirstOrDefault();

                } catch (Exception ex) {
                    Console.WriteLine(ex.Message);
                    throw;
                }
            }
        }
        //    public class MiscContextInitializer : DropCreateDatabaseIfModelChanges<Misc>{
        //        protected override void  Seed(Misc context)
        //{
        //    Father f = new Father();
        //            f.Name = «Dad»;
        //           context.Fathers.Add(f);
        //            base.Seed(context);
        //}
        // }
    }

Answers

  • Hi Rich;

    The error states to add a reference to System.Data.Entity.dll you have the using statement System.Data.Entity which is also needed.

    In Solution Explorer right click on the Reference node in the project tree and select add a reference. When the new dialog box opens in the .Net tab find and select System.Data.Entity.dl, then recompile and try.


    Fernando (MCSD)

    If a post answers your question, please click «Mark As Answer» on that post and «Mark as Helpful«.

    • Proposed as answer by

      Tuesday, September 13, 2011 8:23 AM

    • Marked as answer by
      Jackie-Sun
      Monday, September 26, 2011 6:28 AM

Понравилась статья? Поделить с друзьями:
  • Using render selected with empty selection ошибка
  • Usb unknown device windows 7 код ошибки 43
  • Uwow ошибка подключения к серверу
  • Using namespace system c ошибка
  • Uwow ошибка подключения blz51900003