add a sql query result to a class - c#

im trying to add a single row to a class using linq to sql.
i have a table (AdressesTable) wich contains a key named ID and an adress1 and adress2 column...
i created a class:
public class Adresses
{
public int ID { get; set; }
public int adress1 { get; set; }
public int adress2 { get; set; }
}
i created a datacontext and wrote a query
DBDataContext db = new DBDataContext();
Adresses adr = (from p in db.AdressesTable
where p.ID ==1
select p).First();
but it's not working... how can i add a sql query result to a class object?

You need to build a DbContext like this:
public class MyDbContext : DbContext
{
public DbSet<Addresses> Addresses { get; set; }
}
and then you can use it like this:
var db = new MyDbContext();
var adr = (from p in db.Addresses
where p.ID == 1
select p).First();

Related

LINQ To Entity - Inner Join issue

I have two related tables like below :
Users :
public partial class Users
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Users()
{
}
public int ID { get; set; }
public int UserType_ID { get; set; }
public string Email { get; set; }
public virtual UserTypes UserTypes { get; set; }
}
UserTypes :
public partial class UserTypes
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public UserTypes()
{
this.Users = new HashSet<Users>();
}
public int ID { get; set; }
public string Name { get; set; }
public string Title { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Users> Users { get; set; }
}
For access Name of UserType i wrote this linq to entity :
string[] UserTypes = new string[1];
using (Crypto_Entities entities = new Crypto_Entities())
{
int User_ID_Integer = int.Parse(User_ID.Trim());
var user = (from User in entities.Users
//join UserType in entities.UserTypes on User.UserType_ID equals UserType.ID
where User.ID == User_ID_Integer
select User).FirstOrDefault();
if (user != null)
{
UserTypes[0] = user.UserTypes.Name;
}
}
My question is why user.Name does not work for my purpose and what is the benefit of join in linq to entity?
If i remove join as i did in my query i still can see Name field of UserType with user.UserTypes.Name.
You do not need join if you have defined correctly navigation properties. And if you just need Name, do not retrieve full entity.
string[] UserTypes = new string[1];
using (Crypto_Entities entities = new Crypto_Entities())
{
int User_ID_Integer = int.Parse(User_ID.Trim());
var query =
from User in entities.Users
where User.ID == User_ID_Integer
select User.UserTypes.Name;
var name = query.FirstOrDefault();
if (name != null)
{
UserTypes[0] = name;
}
}
If you use navigation property in query, EF automatically generates all needed joins. But if you just select whole entity without defining Include - EF will not load related data. It makes sense, because otherwise you may load almost whole database if there are a lot of relations.
Since you have set up the relations in your entities you don't need to manually write join to load related data:
var user = entities.Users
.Include(u => u.UserTypes)
.Where(u => u.ID == User_ID_Integer)
.FirstOrDefault();
As for your join being useless - EF Core translates the code into actual SQL (which you can check) and since you are not selecting any data from the joined table - it is as useless as it would be in SQL query where you have selected fields only from one table of join result.

Comparing two table IDs. ASP.NET MVC

I am currently loading two Orders and Colors tables, I wanted the Colors table to list the items that have the ID equal to Orders. For this, what occurred to me was to assign the IdOrders values ​​to a variable and compare it with my IdOrders (in my table Colors), but it is not possible to assign the database's balance to my variable
My tables:
public partial class Orders
{
public int ID_Orders { get; set; }
public Nullable<System.DateTime> Data_Registo { get; set; }
public string Num_Encomenda { get; set; }
public string Ref_Cliente { get; set; }
}
public partial class Colors
{
public int ID_Orders { get; set; }
public int ID_Programa_Malha { get; set; }
public int ID_Linha_Cor { get; set; }
public string Cor { get; set; }
}
I am working with a database already in operation and possible these tables are already used in a sql join but not how to process that information.
As I said the first thing I remembered was to do this:
My Controller:
var id = from d in db.Orders
select d.ID_Orders;
var color = db.Colors.Where(x => x.ID_Orders = id).ToList();
var tables = new EncomendaViewModel
{
Orders= db.Orders.ToList(),
Colors= color.ToList(),
};
return View(tables);
Error in id: CS0029 C# Cannot implicitly convert type to 'int'
Is it possible to process the data in this way?
Thanks for anyone who can help!
-------------------(Update)------------------------------------------------
Using == cs0019 operator '==' cannot be applied to operands of type
My view in Broswer
dbEntities sd = new dbEntities();
List<Orders> orders= sd.Orders.ToList();
List<Colors> colers= sd.Colors.ToList();
var multipletable = from c in orders
join st in colers on c.ID_Programa equals st.ID_Programa into table1
from st in table1.DefaultIfEmpty()
select new MultipleClass { orders= c, colers= st };
There could be one or more values returned from the below query.
var id = from d in db.Orders
select d.ID_Orders;
That is the reason why it was throwing an error.
So lets try it this way
var color = db.Colors.Where(x => id.Contains(x.ID_Orders)).ToList();
public class OrderWithColorsViewModel
{
public Order order { get; set; }
public List<Colors> colers{ get; set; }
}
Public class TestOrderController : Controller
{
public DailyMVCDemoContext db = new DailyMVCDemoContext();
public ActionResult Index()
{
var orders= db.Orders.ToList();
var colers = db.Colors.ToList();
var result = (from c in orders
join st in colers on c.ID_Orders equals st.id into table1
select new OrderWithColorsViewModel { order =c, colers =
table1.ToList() }).ToList();
return View(result);
}
}
credits: YihuiSun

Data access using Entity Framework in ASP.NET MVC

I have a table with these columns(type) as described below.
TABLE
------------------------------------------------------------------
Dir(str) | Twnshp(int) | Rng(int) | Section(int) | Xcell(int) | Ycell(int)
------------------------------------------------------------------
I am trying to do this query using EF.
SELECT Xcell,Ycell FROM [CIR].[dbo].[TRS2Cell] where Twnshp = 1 and Rng = 4 and Section =31
After some study, I created a DAL Context and class as below.
PlotXYContext.cs
public class PlotXYContext :DbContext
{
public DbSet<PlotXY> XYCells { get; set; }
}
PlotXY.cs
[Table("TRS2Cell")]
public class PlotXY
{
public string Dir { get; set; }
[Key]
public int Twnshp { get; set; }
public int Rng { get; set; }
public int Section { get; set; }
public int Xcell { get; set; }
public int Ycell { get; set; }
}
Here is the code in my controller where I pass the three parameters.
PlotXYContext plotXYContext = new PlotXYContext();
var query = from TRS2Cell in plotXYContext.XYCells
where TRS2Cell.Twnshp == 1
&& TRS2Cell.Rng == 4
&& TRS2Cell.Section == 31
select TRS2Cell.Xcell;
I need help with EF as I am new to it and also is this the right query?
If so how do I retrieve the Xcell and Ycell values from the query.
Also the table has no unique column, no nulls, nothing needs to be updated here. All I want is to do a select.
Normally your not gonna want to do any data access code in your controller. You want to keep those separated.
Also when I first started using EF i got hung up on DB Context as well when I started with MVC. If you added your Ado.Net Entity Data Model correctly the db context should be automatically created for you. If you look at "YourEntity".cs file under "Entity".edmx => "Entity".Context.tt it will look something like
public partial class VuittonEntities : DbContext
{
public VuittonEntities()
: base("name=VuittonEntities")
{
}
To help you out with EF I'm gonna post all my code for a query.
So your Model class in the models folder will look like.
public class RoleGridViewModel
{
public int UserID { get; set; }
public string UserFirst { get; set; }
public string UserLast { get; set; }
public string UserRole { get; set; }
public string UserRoleDesc { get; set; }
}
This is your Data Access layer function: Here I'm creating a list of my model class because I'm gonna populate it in a gridview later on.
public List<RoleGridViewModel> GridRoles()
{
using (VuittonEntities db = new VuittonEntities())
{
return (from users in db.User
join roles in db.UserRole on users.RoleID equals roles.RoleID
select new RoleGridViewModel
{
UserID = users.UserID,
UserFirst = users.FirstName,
UserLast = users.LastName,
UserRole = roles.Role,
UserRoleDesc = roles.Role_Desc
}).ToList();
}
}
Here in your Controller you can call it like this. Normally you would call a businezz layer from your controller I'm going straight to the Data layer to show you how its done. Here var roles holds your query. I'm using Json result here but this can also be done in an action result
public JsonResult RolesGrid()
{
var roles = new UserDAL().GridRoles();
return Json(roles, JsonRequestBehavior.AllowGet);
}
If you just want to select a single item you have to use .First() at the end of the query like this...
public string currentRole(UserViewModel uvm)
{
using (VuittonEntities db = new VuittonEntities())
{
return (from us in db.User
join usRole in db.UserRole on us.RoleID equals usRole.RoleID
where (us.RoleID == uvm.RoleID) && (us.UserID == uvm.UserID)
select usRole.Role).First();
}
}
I found that I wasn't using the similar datatype as in my table to declare the class for it.Thant is the only issue I came across that resolved it and hence the error.
Thank you for all the replies.

Linq to Entities subquery to fill array?

New at linq to entities trying to figure this out. I have the following tables:
Customer: Cust_Id, Name
Orders: Order_Id
CustomerOrders: Cust_Id, Order_Id
I have a class like so:
public class Customers
{
public List<Row> Rows { get; set; }
public Customers()
{
Rows = new List<Row>();
}
public class Row
{
public int Key { get; set; }
public string Name { get; set; }
public List<string> Order_Ids { get; set; }
}
}
Linq query is like this:
var query = from c in context.Customer
select new Customers.Row
{
Key = c.Cust_Id,
Name = c.Name,
Order_IDs = List<string>( ?? )
};
foreach (var row in query)
{
Customers.Rows.Add(row);
}
var serializer = new JavaScriptSerializer();
return serializer.Serialize(Customers);
Where I have '??', can I use a subquery or something to get a list of Order_Id's from the CustomerOrders table?
Right Now, I can only think to loop through the Customers table once it is filled and then query the DB again to get each array of Order Id's for each Customer.
If it's not a requirement, drop the "Row" collection from the "Customer" object. This should suffice:
public class Customer
{
public int Key { get; set; }
public string Name { get; set; }
public List<string> Order_Ids { get; set; }
}
Then you can query like this:
var customers = from c in context.Customers
select new Customer
{
Key = c.Cust_Id,
Name = c.Name,
Order_IDs = c.Orders.Select(o => o.Order_Id).ToList()
};
It's better to deal in objects when writing C# and using EF, than to deal in terms of tables and rows -less confusing.
Try something like this:
var query = from c in context.Customer
select new Customers.Row
{
Key = c.Cust_Id,
Name = c.Name,
Order_Ids = c.Rows.Select(row => row.Key.ToString()).ToList()
};
Where you have .Select(row => row.Key.ToString()) you can set the property you need (Key, Name, etc...). Select method is an extension method to IEnumerable and it return a collection of type of property you have seted, in this case, a collection of strings because I converted it with ToString() method.

Can I create nested classes when using Linq-To-Entities?

I'm still learning Entity Framework and Linq-To-Entities, and I was wondering if a statement of this kind is possible:
using (var context = new MyEntities())
{
return (
from a in context.ModelSetA.Include("ModelB")
join c in context.ModelSetC on a.Id equals c.Id
join d in context.ModelSetD on a.Id equals d.Id
select new MyModelA()
{
Id = a.Id,
Name = a.Name,
ModelB = new MyModelB() { Id = a.ModelB.Id, Name = a.ModelB..Name },
ModelC = new MyModelC() { Id = c.Id, Name = c.Name },
ModelD = new MyModelD() { Id = d.Id, Name = d.Name }
}).FirstOrDefault();
}
I have to work with a pre-existing database structure, which is not very optimized, so I am unable to generate EF models without a lot of extra work. I thought it would be easy to simply create my own Models and map the data to them, but I keep getting the following error:
Unable to create a constant value of type 'MyNamespace.MyModelB'. Only
primitive types ('such as Int32, String, and Guid') are supported in
this context.
If I remove the mapping for ModelB, ModelC, and ModelD it runs correctly. Am I unable to create new nested classes with Linq-To-Entities? Or am I just writing this the wrong way?
What you have will work fine with POCOs (e.g., view models). Here's an example. You just can't construct entities this way.
Also, join is generally inappropriate for a L2E query. Use the entity navigation properties instead.
I have created your model (how I understand it) with EF 4.1 in a console application:
If you want to test it, add reference to EntityFramework.dll and paste the following into Program.cs (EF 4.1 creates DB automatically if you have SQL Server Express installed):
using System.Linq;
using System.Data.Entity;
namespace EFNestedProjection
{
// Entities
public class ModelA
{
public int Id { get; set; }
public string Name { get; set; }
public ModelB ModelB { get; set; }
}
public class ModelB
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ModelC
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ModelD
{
public int Id { get; set; }
public string Name { get; set; }
}
// Context
public class MyContext : DbContext
{
public DbSet<ModelA> ModelSetA { get; set; }
public DbSet<ModelB> ModelSetB { get; set; }
public DbSet<ModelC> ModelSetC { get; set; }
public DbSet<ModelD> ModelSetD { get; set; }
}
// ViewModels for projections, not entities
public class MyModelA
{
public int Id { get; set; }
public string Name { get; set; }
public MyModelB ModelB { get; set; }
public MyModelC ModelC { get; set; }
public MyModelD ModelD { get; set; }
}
public class MyModelB
{
public int Id { get; set; }
public string Name { get; set; }
}
public class MyModelC
{
public int Id { get; set; }
public string Name { get; set; }
}
public class MyModelD
{
public int Id { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
// Create some entities in DB
using (var ctx = new MyContext())
{
var modelA = new ModelA { Name = "ModelA" };
var modelB = new ModelB { Name = "ModelB" };
var modelC = new ModelC { Name = "ModelC" };
var modelD = new ModelD { Name = "ModelD" };
modelA.ModelB = modelB;
ctx.ModelSetA.Add(modelA);
ctx.ModelSetB.Add(modelB);
ctx.ModelSetC.Add(modelC);
ctx.ModelSetD.Add(modelD);
ctx.SaveChanges();
}
// Run query
using (var ctx = new MyContext())
{
var result = (
from a in ctx.ModelSetA.Include("ModelB")
join c in ctx.ModelSetC on a.Id equals c.Id
join d in ctx.ModelSetD on a.Id equals d.Id
select new MyModelA()
{
Id = a.Id,
Name = a.Name,
ModelB = new MyModelB() {
Id = a.ModelB.Id, Name = a.ModelB.Name },
ModelC = new MyModelC() {
Id = c.Id, Name = c.Name },
ModelD = new MyModelD() {
Id = d.Id, Name = d.Name }
}).FirstOrDefault();
// No exception here
}
}
}
}
This works without problems. (I have also recreated the model from the database (which EF 4.1 had created) in EF 4.0: It works as well. Not surprising since EF 4.1 doesn't change anything in LINQ to Entities.)
Now the question is why you get an exception? My guess is that there is some important difference in your Models or ViewModels or your query compared to the simple model above which is not visible in your code example in the question.
But the general result is: Projections into nested (non-entity) classes work. (I'm using it in many situations, even with nested collections.) Answer to your question title is: Yes.
What Craig posted does not seem to work for nested entities. Craig, if I am misunderstood what you posted, please correct me.
Here is the workaround I came up with that does work:
using (var context = new MyEntities())
{
var x = (
from a in context.ModelSetA.Include("ModelB")
join c in context.ModelSetC on a.Id equals c.Id
join d in context.ModelSetD on a.Id equals d.Id
select new { a, b, c }).FirstOrDefault();
if (x == null)
return null;
return new MyModelA()
{
Id = x.a.Id,
Name = x.a.Name,
ModelB = new MyModelB() { Id = x.a.ModelB.Id, Name = x.a.ModelB..Name },
ModelC = new MyModelC() { Id = x.c.Id, Name = x.c.Name },
ModelD = new MyModelD() { Id = x.d.Id, Name = x.d.Name }
};
}
Since Entity Framework can't handle creating nested classes from within the query, I simply returned an anonymous object from my query containing the data I wanted, then mapped it to the Model

Categories

Resources