return all IQueryable with Entity framework - c#

I just switched from Linq to entities framework, and I'm having problems with methods that returns "all rows". I get: "The type 'System.Data.Objects.DataClasses.EntityObject' is defined in an assembly that is not referenced" error in my "service layer" that calls the data-layer.
I get an error on:
BookingObjectRepository _repository = new BookingObjectRepository();
public IQueryable<BookingObject> GetBookingObjects()
{
return _repository.GetBookingObjects();
}
and in the "data-layer" I have:
BookingsystemEntities _entities = new BookingsystemEntities();
public IQueryable<BookingObject> GetBookingObjects()
{
return from bo in _entities.BookingObjectSet
select bo;
}
UPDATE: Filter items, they are "physically" in Filters-folder but namespace is same as the emdx file uses.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BookingSystem.Data.Models
{
public static class BookingObjectFilters
{public static IQueryable<BookingObject> ByBookingObjectID(this IQueryable<BookingObject> qry, int bookingobjectID)
{
return from bo in qry
where bo.BookingObjectID == bookingobjectID
select bo;
}

Your system must have .NET 3.5 SP 1 or better installed, and your project must reference the System.Data.Entity assembly (look at the references node in Solution Explorer).

Do you have
using System.Data;
using System.Data.Objects.DataClasses;
in your usings?
and
public IQueryable GetBookingObjects() { return _repository.GetBookingObjects(); }
should probably be
public IQueryable<BookingObject> GetBookingObjects() { return _repository.GetBookingObjects(); }
Hope that helps,
Dan

Related

Why does this IQueryable issue give me an error?

I cannot figure out why code below is not working. It is causing a build error:
IQueryable<InventoryTbl>' does not contain a definition for 'FirstOrDefault' and the best extension method overload 'Queryable.FirstOrDefault<AdminModel>(IQueryable<Admin>)
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RuciyanaSweets.Models;
[HttpGet]
public ActionResult AdminAddorEdit(int id = 0)
{
if (id==0)
return View(new Model());
else
{
using (Entities db = new Entities ())
{
return View(db.TableName.Where(x => x.FieldID == id).FirstOrDefault< Model >());
}
}
}
The definition TSource FirstOrDefault<TSource>(this IQueryable<TSource> source) is part of System.Linq namespace. Check that your project referencing to System.Core and you have using System.Linq; and using System.Data.Entity;.
Be sure you installed the EntityFramework package.
Queryable.FirstOrDefault Method

AddAsync() method is missing

I am using Entity Framework Core. I want to create an async method which will create new user in my database, i have included all the libraries I need, but some methods that are supposed to work with database are missing, I have almost every async method but i am missing AddAsync and RemoveAsync. When I type AddAsync manually I get the following error message: "Error CS1061 'DbSet' does not contain a definition for 'AddAsync' and no accessible extension method 'AddAsync' accepting a first argument of type 'DbSet' could be found (are you missing a using directive or an assembly reference?)"
The class where the method is created has following code and libraries included:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using System.Data;
using Microsoft.EntityFrameworkCore;
namespace ClassLibrary
{
public class Class1 : Interface1
{
public async Task AddKorisnik(Korisnici k)
{
using (ExtentEntities context = new ExtentEntities())
{
context.Korisnici.AddAsync();
await context.SaveChangesAsync();
}
}
}
}
The class where the DbContext is used is following:
namespace ClassLibrary
{
using System;
using System.Linq;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class ExtentEntities : DbContext
{
public ExtentEntities()
: base("name=ExtentEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Korisnici> Korisnici { get; set; }
}
}
There is nothing asynchronous with adding an object to an in-memory DbSet<T>. You should use the synchronous Add method to do this.
SaveChangesAsync() is the method that actually connects asynchronously to the underlying database.

Cannot implicitly convert type. An explicit conversion exists (are you missing a cast?)

I am trying to develop a web application using ASP.Net Web API. Now after creating Product model and IProductRepository interface I'm having difficulty in showing all products. I'm getting error message
Cannot implicitly convert type System.Collections.Generic.IEnumerable<WebApplication1.Models.Product> to System.Collections.Generic.IEnumerable<WebApplication1.Product>. An explicit conversion exists (are you missing a cast?)
Controllers\ProductsController.cs 17 20 WebApplication1
on this line of code
return repo.GetAll();
I don't understand what to do. If someone points out the problem and explain me what I'm doing wrong that would be very helpful.
ProductsController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public class ProductsController : ApiController
{
static readonly IProductRepository repo = new ProductRepository();
public IEnumerable<Product> GetAllProducts()
{
return repo.GetAll();
}
}
}
ProductRepository.cs
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace WebApplication1.Models
{
public class ProductRepository : IProductRepository
{
public string cs = System.Configuration.ConfigurationManager.ConnectionStrings["MediaSoftAppEntities"].ConnectionString;
public IEnumerable<Product> GetAll()
{
List<Product> products = new List<Product>();
string sql = String.Format("Select [ProductID], [ProductName], [Price] FROM [Products]");
using (SqlConnection con = new SqlConnection(cs)){
using (SqlCommand cmd = new SqlCommand(sql, con)){
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read()){
Product product = new Product();
product.ProductID = dr.GetInt32(0);
product.ProductName = dr.GetString(1);
product.Price = dr.GetInt32(2);
}
}
}
return products.ToArray();
}
}
}
IProductRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebApplication1.Models
{
public interface IProductRepository
{
IEnumerable<Product> GetAll();
}
}
The error is saying that the compiler thinks that
ProductsController.GetAllProducts wants to return a WebApplication1.Product
but IProductRepository.GetAll returns a WebApplication1.Models.Product instead.
Do you have 2 Product classes in these 2 different namespaces?
Alternatively, maybe you previously had the Product class in the WebApplication1 namespace, and it's now been moved into the WebApplication1.Models namespace, maybe you just have a stale reference and a "Rebuild All" will fix it.

Basics of Entity Framework

In my demo solution, I have a two projects DataAccess and WebInterface.
In DataAccess project, I have one EF for Users and a class file UserDataAccessService.cs
Code in UserDataAccessService.cs:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Data.EntityClient;
using System.Data.SqlClient;
using System.Data;
using DataAccess.User;
namespace DataAccess.User
{
public sealed class UserDataAccessService
{
private string efConnectionString;
private string portalConnectionString;
public string ConnectionString
{
get { return efConnectionString; }
}
public UserDataAccessService(string portalConnectionString)
{
this.portalConnectionString = portalConnectionString;
this.efConnectionString = GetConnectionString(portalConnectionString);
}
private string GetConnectionString(string portalConnectionString)
{
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Provider = "System.Data.SqlClient";
entityBuilder.ProviderConnectionString = portalConnectionString;
entityBuilder.Metadata = "res://*/User.ProgramModel.csdl|res://*/User.UserModel.ssdl|res://*/User.UserModel.msl";
return entityBuilder.ToString();
}
public IEnumerable<User> GetUsers(int? userId, bool? status)
{
using (Users objectContext = new Users(efConnectionString))
{
return objectContext.GetUsers(null, null);
}
}
}
}
Now in WebInterface project, I simply have a ManageUsers.aspx page on which I am trying to fetch list of users by below code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using DataAccess.User;
namespace WebInterface
{
public partial class ManageUser : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
UserDataAccessService usrObj = new UserDataAccessService(ConfigurationManager.ConnectionStrings["portalConn"].ToString());
List<User> userLst = new List<User>();
userLst = usrObj.GetUsers(1, null).ToList();
}
}
}
Problem:-
When I am building the solution then I am getting the below error:-
Error 1
The type 'System.Data.Objects.DataClasses.EntityObject' 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:\Practice\PTP\UI\WebInterface\User\ManageUser.aspx.cs
18 13
WebInterface
To fix it, I have included it System.Data.Entity.dll in reference folder of WebInterface project which has fixed the issue.
My Question:
If you look into my the code then you can that code related EF is all in DataAccess project which has all required dll reference in it required for classes related to EF.
and in WebInterface project I have included DataAccess.dll and in it .aspx page I am simply calling it function to the fetch data.
Then why it requires System.Data.Entity.dll in WebInterface project too?
Regards
Varun
I am only 99% sure cause you are using some old school EF :) and you didn't share User class but... I think it's the User class that is EntityFramework aware. Is it the case that User inherits from EntityObject?
You can avoid that by mapping data from entity classes to you UI classes. But that takes all the magic from using EF.

The name 'ninja' does not exist in the current context

With the below code I get thee following error:
NinjaSteps.cs(16,13): error CS0103: The name 'ninja' does not exist in the current context
The command line I use to compile is:
csc /target:library /reference:C:\Ruby193\lib\ruby\gems\1.9.1\gems\
cuke4nuke-0.4.0\dotnet\Cuke4Nuke.Framework.dll /reference:C:\Fitnesse\FitNesseRo
ot\jediwhale-fitsharp-a78d820\binary\tools\nunit\framework\nunit.framework.dll /
reference:C:\Users\Rahul\Documents\Visual~1\Projects\ConsoleApplication3\Console
Application3\Ninja.dll NinjaSteps.cs
The code I am trying to compile is from a tutorial on Cucumber automation technology:
NinjaSteps.cs:
http://cuke4ninja.com/sec_ninja_survival_net.html
using System;
using System.Collections.Generic;
using System.Text;
using Cuke4Nuke.Framework;
using NUnit.Framework;
using NinjaSurvivalRate;
namespace ConsoleApplication3
{
class NinjaSteps
{ [Given(#"^the ninja has a ([a-z]*) level black-belt$")]
public void TheNinjaHasABlackBelt(String level)
{ ninja = new Ninja(level);
}
[When(#"^attacked by [a\s]*(.*)$")]
public void AttackedBy(String opponent)
{
actions = ninja.AttackedBy(opponent);
}
[Then("^the ninja should (.*)$")]
public void TheNinjaShould(String action)
{
Assert.IsTrue(actions.Contains(action));
}
}
}
Ninja.cs is below, compiled to Ninja.dll:
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
namespace NinjaSurvivalRate
{
public class Ninja
{
public Ninja(String beltLevel)
{
}
public List<String> AttackedBy(String opponent)
{
if ("Chuck Norris" == opponent)
return new List<string>(
new String[] { "run for his life" });
else
return new List<string>(
new String[] { "engage the opponent" });
}
}
}
Answers and feedback will be appreciated. Going through similar threads, I found that the resolution depended on a case by case basis and their was no consistent root cause, and felt I had to detail exact code details to get an understanding of the cause. You time and help will be greatly appreciated. Thanks.
You haven't defined the variable ninja. You need:
var ninja = new Ninja(level);
Do the same for actions.
EDIT:
Actually both the variables are supposed to be fields/properties in the class itself, if I understand your intentions correctly.
The tutorial is not telling you the whole history. If you go to the source code you will see that there is actually a field ninja declared that is initialized in the method TheNinjaHasABlackBelt (that you already have).

Categories