Join two tables in nhibernate mvc c# - c#

I am joining two tables using primary key and foreign key.
My tables are
Item, Columns are:
ItemId int primary key,
Name varchar,
Price float,
CategoryID int foreign key,
QtyInStock int
Category, Columns are:
Id int pk,
Category varchar,
Name varchar
I want to select Category on basis of ID=categoryId
I am using NHibernate 4.03 with xml configuration files.

For unrelated entities:
var query = from item in session.Query<Item>()
join category in session.Query<Category>() on item.CategoryID equals category.Id;
For related entities:
Category catAlias = null;
var query = session.QueryOver<Item>()
.JoinAlias(x => x.Category, () => catAlias);

Related

EF Core, navigation property HasMany / WithMany without join table

I have two tables:
Table Cards with the following Columns:
Id (Unique Index/Primary Key)
OracleId (Guid, NOT Unique)
CardName
CardText
SetName
...
Table CardRulings:
OracleId (Guid, Indexed, NOT Unique)
Source
Comment
I'm looking for a simple navigation property. Card.Rulings should have a collection (ICollection<CardRuling>) of associated CardRulings from the table. CardRulings is a keyless table and there are duplicate OracleId's in both the Cards and CardRulings table. This isn't quite a HasMany/WithMany as there is no key technically in either table, and there is no "unique" index that links the two tables together.
Try this:
var cards = _dbContext.Cards.select(c=>new CardsDTO(){
Id = c.Id,
OracleId= c.OracleId,
CardName = c.CardName,
CardText = c.CardText,
SetName = c. SetName,
CardRulings = new List<CardRulings>();
});
var cardRuling = _dbContext.CardRulings.ToList();
foreach(var item in cards){
item.CardRulings = cardRuling.Where(f=> f.OracleId = item.OracleId).ToList()
}

ADO Entity Builder won't generate class for table with just foreign keys

I have a SQL table that has two foreign keys and when I run Entity Data Model Wizard and select Code First from database, and then create the tables, my table won't show up as a class. It generates something in the primary model class that looks like this:
modelBuilder.Entity<User>()
.HasMany(e => e.Categories)
.WithMany(e => e.Users)
.Map(m => m.ToTable("UserCategory").MapLeftKey("UserID").MapRightKey("ID"));
But I don't know how to use that to add or delete from that table, since it won't show up as a class when I'm coding.
My tables are:
CREATE TABLE [User]
(
ID NVARCHAR(128) PRIMARY KEY,
FirstName VARCHAR(255) NOT NULL,
LastName VARCHAR(255),
JoinDate DATETIME,
ZipCode VARCHAR(25),
SearchRadius INT,
LoginToBusinessSide BIT
);
/*The categories businesses can fall under. */
CREATE TABLE Category
(
ID INT IDENTITY(1,1) PRIMARY KEY,
[Name] VARCHAR(255) UNIQUE NOT NULL,
);
/*The categories chosen by a specific user to get notified of*/
CREATE TABLE UserCategory
(
ID INT FOREIGN KEY REFERENCES Category(ID),
UserID NVARCHAR(128) FOREIGN KEY REFERENCES [User](ID),
CONSTRAINT PK_UserCategory PRIMARY KEY (ID, UserID)
);
How do I get UserCategory to show up as its own class, so I can easily access it?
I want to be able to just access it like every other class:
db.UserCategories.ID =
How can I
ADO doesn't create a class for my many to many table, but I can still access it. To add new categories to it, I use this code:
for(var i = 0; i < categories.Length; ++i)
{
var user = db.Users.Find(thisUser.ID);
var cat = db.Categories.Find(categories[i]);
user.Categories.Add(cat);
}
I have to an active connection to both tables that the foreign keys are linked to, and then when I add one to the Categories table, it goes to the correct place.
If you understand exactly why this works, or if there's a better way, please do comment.

How can I convert SQL to lambda expressions

In my database, I created the tables structure as follows.
CREATE TABLE Course
(
Course_ID int IDENTITY(1,1) PRIMARY KEY,
Name varchar(255) NOT NULL,
);
CREATE TABLE Student
(
Stu_ID int IDENTITY(1,1) PRIMARY KEY,
Name varchar(255) NOT NULL,
Mobile varchar(255),
Age int,
Course_ID int,
FOREIGN KEY (Course_ID) REFERENCES Course(Course_ID)
);
CREATE TABLE Subject
(
Sub_ID int IDENTITY(1,1) PRIMARY KEY,
Name varchar(255) NOT NULL,
);
CREATE TABLE Teacher
(
Teach_ID int IDENTITY(1,1) PRIMARY KEY,
Name varchar(255) NOT NULL,
Mobile varchar(255)
);
CREATE TABLE Course_Subject
(
CouSub_ID int IDENTITY(1,1) PRIMARY KEY,
Course_ID int,
Sub_ID int,
FOREIGN KEY (Course_ID) REFERENCES Course(Course_ID),
FOREIGN KEY (Sub_ID) REFERENCES Subject(Sub_ID)
);
CREATE TABLE Teacher_Subject
(
TeachSub_ID int IDENTITY(1,1) PRIMARY KEY,
Teach_ID int,
Sub_ID int,
FOREIGN KEY (Teach_ID) REFERENCES Teacher(Teach_ID),
FOREIGN KEY (Sub_ID) REFERENCES Subject(Sub_ID)
);
Now my problem is I need to retrieve students data who learned from some teacher, which means need to retrieve some teacher's students who learned from his/her. To accomplish my requirement. I write this SQL query.
select
s.*
from
tbl_student s
inner join
Course_Subject tcs on s.Course_Id = tcs.Course_Id
inner join
Teacher_Subject tst on tst.Sub_ID = tcs.Sub_ID
inner join
Teacher t on t.Teach_ID = tst.Teach_ID
where
t.Teach_ID = #SomeTeacherId
Now I need to convert this query to a lambda expression or Linq. How can I do it? Please help me. Have any possible way to generate this using Visual Studio.
Well, you could use EF to generate object mapping to your tables. And use LINQ to rewrite your query with a slightly different syntax:
var result = from students in tbl_student
join subjects in Course_Subject on students.Course_Id == subjects.Course_Id
join ts in Teacher_Subject on subjects.Sub_ID == ts.Sub_ID
join teachers in Teacher on teachers.Teach_ID == ts.Teach_ID
where teachers.Teach_ID == "your_value"
select students;
Not sure it's an absolutely correct query, but I hope you'll get the main idea.
Have any possible way to generate this using Visual Studio.?
Yes, you can do this using Linq-to-SQL
for your query, this might be appropriated
var students = from student in db.Students
join tcs in db.CourseSubjects on student.CourseId equals tcs.CourseId
join tst in db.TeacherSubjects on tcs.SubId equals tst.SubId
join t in db.Teachers on tst.TeachId equals t.TeachId
where t.TeachId == someTeacherId
select student;
Lambda:
Students
.Where(x=> x.Course.Course_Subjects
.Any(y => y.Subject.Teacher_Subjects
.Any(z => z.Teach_ID == someTeacherId)
)
)
.Select(x => x)

Update column name in three tables in c#

i have 3 tables mainCategory, subCategory and products.i want to update main category but by the time it should update the respected data in other remaining tables too.following ar my tables.
1. mainCategory
mainCatId
mainCatName
2. subCategory
subCatId
mainCatId
mainCatName
subCatName
3. products
productId
subCatId
subCatName
productName
update has to be like,when i change mainCatName it automaticaly changes mainCatId,so it should be change mainCaId and mainCatName,subCatId and subCatName in other tables too, i have tried a query but its not working
query is:
UPDATE mainCategory
SET mainCatId =, mainCatName =
FROM mainCategory
INNER JOIN
subCategory ON mainCategory.mainCatId = subCategory.mainCatId
CROSS JOIN
products
,kindly help me out!
You need to link your tables with a Foreign Keys and apply ON UPDATE CASCADE in table definition.
You do not need to have mainCatName in subCategory table, because subCategory table should be linked with a foreign key with a mainCategory table.
Same thing with a subCatgoryName in products table.
CREATE TABLE mainCategory (
[mainCatId] INT NOT NULL,
[mainCatName] NCHAR (10) NULL,
PRIMARY KEY CLUSTERED ([mainCatId] ASC));
CREATE TABLE subCategory (
[subCatId] INT NOT NULL,
[mainCatId] INT NULL,
[subCatName] NCHAR (10) NULL,
PRIMARY KEY CLUSTERED ([subCatId] ASC),
CONSTRAINT [FK_Table_ToTableMainCat] FOREIGN KEY ([mainCatId])
REFERENCES [mainCategory] ([mainCatId]) ON UPDATE CASCADE);
CREATE TABLE products (
[productId] INT NOT NULL PRIMARY KEY,
[subCatId] INT NULL,
[productName] NCHAR(10) NULL,
CONSTRAINT [FK_products_ToTableSubCategory] FOREIGN KEY (subCatId)
REFERENCES subCategory(subCatId) ON UPDATE CASCADE);
You can update mainCatName simply by:
UPDATE mainCategory SET mainCatName='NEW NAME' WHERE mainCatId=SOMEID;
Your subCategory table linked with a mainCategory table through a FOREIGN KEY.
Your products table linked with a subCategory table with a FOREIGN KEY.
If you want to get the products of the particular mainCategory:
SELECT productName, subCatName, mainCatName FROM products
JOIN subCategory ON products.subCatID = subCategory.subCatID
JOIN mainCategory ON subCategory.mainCatID = mainCategory.mainCatID
where mainCategory.mainCatID = 1;
If you want to get the products of the particular subCategory:
SELECT productName, subCatName FROM products
JOIN subCategory ON products.subCatID = subCategory.subCatID
where subCategory.subCatID = 1;
If you want to delete the products from a particular subCategory, you just delete the subcategory record and corresponding products will be deleted on cascade.
If you want to change the Name of the subCategory, you just change the record in the subCategory table.

Fluent NHibernate join not using primary key

I am trying to get a single property from a joined table where a non-PK in my main table is joined to the PK of the foreign table. Below is an oversimplified example of what I am trying to accomplish (I do not want to reference the foreign entity):
Tables:
CREATE TABLE Status
(
Id int,
Body text,
CategoryId int
)
CREATE TABLE Category
(
Id int,
Name text
)
SQL to generate:
SELECT Id, Body, CategoryId, Category.Name AS CategoryName
FROM Status
LEFT JOIN Category ON Category.Id = Status.CategoryId
I am trying to map the join like this in the StatusMap but it seems to be joining on the two primary keys (where Status.Id = Category.Id):
Join("Category" m =>
{
m.Optional();
m.KeyColumn("CategoryId");
m.Map(x => x.CategoryName, "Name");
});
As far as I know the only way around this using Fluent is to map to a view as you currently are doing. Join() will always map to the primary key of the parent table. The KeyColumn method specifies the key column for the child table only, which in your case is the Category table.
To achieve the desired SQL using your simplified version above you'd probably want to use References to define a many-to-one relationship between status and category.

Categories

Resources