LINQ to SQL query in related tables - vb.net

I have a library database with related tables.
dbo.boeken (books) that only have the general data of a book.
PK is BoekID
There is a relationship with dbo.BoekenGegevens (Book data). These data for the book are the author, publisher and nur codes. An author and publisher have written and published several books.
FK is BoekID
(The other FK's belongs to Author / Publisher etc.)
The other table has the details of who owns the book.
FK is BoekID
A book can be owned by several libraries.
Now I want to do a search with a Linq query on the title of a book.
How do I build a LINQ query so that I only see the books that belong to the requesting library?
The Datasets:
Private dbBoeken As New BoekenDataContext
Private dbBoekenGemeenten As New BoekenGemeentenDataContext
Private dbBoekenGegevens As New BoekenGegevensDataContext
Code i use:
Dim searchTitle = From title In dbBoeken.Boekens
Where title.Titel = txtTitle.Text
Join bookid In dbBoekenGegevens.BoekenGegevens On bookid.BoekID Equals title.BoekID
Select title
dbGridView.DataSource = searchTitle
Error when execute the query:
System.InvalidOperationException: The query contains references to items defined in a different data context.

Related

Updating object with related objects with EntityFramework 6

I'm trying to integrate EF6 database first into a project, which uses legacy sql. I have a problem with the following tables:
Product(ID, Name) -- this translates to a Product entity
User(ID, Name) -- this translates to a User entity
UserXProduct(UserID, ProductID) -- this translates into navigational properties
Note that I can't access UserXProduct table through entity framework, because it somehow didn't generate a new table, just the navigational properties. I use the following code to update the table:
var entity = ctx.User.SingleOrDefault(rec => rec.ID == updRec.ID);
if(entity != null){
entity.Product = ctx.Product.Where(rec => updRec.ProductIDs.Contains(rec.ID)).ToList();
ctx.SaveChanges();
}
It works the first time around, when the User record doesn't have any Products associated with it, whenever I add another product to the list, it fails.
SQL Profiler shows, that Entity Framework tries to INSERT UserID and ProductID into UserXProduct table, not just the new one, but all of them. It should either delete previous connections or insert only new ones. How can I achieve such behaviour?

SOLR open search on multiple tables

Say I have authors,publishers,books where authors or publishers may have zero books stored in my DB
how do I index (i.e. config data-congig.xml / schema.xml) my tables so my users can freely type a book title, a publisher or author name and find some results?
1.Make author, publisher, book_title fields in schema and define these filed in qf( query fields) in solr query.
2.You can make a single filed having name of author concatenated with publisher and book title for each book. Make documents book wise. Match searched string in that field it will return all possible results.

Merge objects within Entity Framework?

I'm attempting to create a merge function, in my application i have a users object that has PK/FK relationship to other objects relating to that user. (for my example say Contact is the object, and Orders have a 1:Many relationship to Contacts.
The function would pass in two EF objects, with one being the "kept" record and the other being "merged". Whereby all data in the kept should win should there be duplicate field entry. This is all easy enough, but i can't understand how to point all the link objects to the new record PK/FK issue.
How can this be achieved within EF(Design first)?
Example code from MS - Can i simply load the objects related to the merge and change their FK relationship? (differentcontact in example below). Such that say a Contact was created twice, and orders exist under both Contacts, we want to keep the first Contact, and remove the duplicate one. First we must re-assign all the orders to the correct contact (differentcontact), and then would be able to remove the duplicate contact value?
Using context As New POCOAdventureWorksEntities()
Dim orderId As Integer = 43659
Dim differentContactID As Integer = 5
Dim order As Order = context.Orders.Include("Contact").Where(Function(o) o.SalesOrderID = orderId).First()
Dim differentContact As Contact = context.Contacts.First(Function(c) c.ContactID = differentContactID)
order.ContactID = differentContact.ContactID '// Something like this?
context.SaveChanges()

how to update data into table in sql database using django

I have learned about the database concepts in django tutorial book. I have some doubts about to fetch data from the table in sql database server. In django book they explained something like this to filter data as like as below
Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')
Here Entry is the class name which is defined in models.py file like below
models.py
class Entry(models.Model):
blog = models.ForeignKey(Blog)
headline = models.CharField(max_length=255)
body_text = models.TextField()
pub_date = models.DateField()
mod_date = models.DateField()
authors = models.ManyToManyField(Author)
n_comments = models.IntegerField()
n_pingbacks = models.IntegerField()
rating = models.IntegerField()
def __str__(self): # __unicode__ on Python 2
return self.headline
In the above method there is nothing mention about the table to modified. Then which table it is going to be modified in the below query.
Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')
If i asked anything wrong please forgive me. Can anyone clear my doubts.
From the docs on table names:
To save you time, Django automatically derives the name of the database table from the name of your model class and the app that contains it. A model’s database table name is constructed by joining the model’s “app label” – the name you used in manage.py startapp – to the model’s class name, with an underscore between them.
For example, if you have an app bookstore (as created by manage.py startapp bookstore), a model defined as class Book will have a database table named bookstore_book.
To override the database table name, use the db_table parameter in class Meta.
You don't need to know the table name, if you use the API like you have listed:
Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')
Django will know what table to update, because of the model you have referenced.
The name of table is determined by model parameter "table_name". If you don't specified it, django automatically derives the name of the database table from the name of your model class and the app that contains it: https://docs.djangoproject.com/en/dev/ref/models/options/#db-table
If your question is about performing SQL queries in django, this will be helpful: https://docs.djangoproject.com/en/dev/topics/db/sql/

Querying many to many relationship

Every article I need to solve my problem seems to be in C# and I need a solution in VB.NET.
I'm using EF 6.0 with Database First model. Let me use the classic Customer product scenario to demonstrate my situation. In my database I have three tables Customer, Product and CustomerProduct. See this example in this link as mine is exactly the same.
After I generate my model from the database, my entity model diagram shows that the CustomerProduct has disappeared as expected and the the model shows a many to many relationship between Customer and Product also as expected with navigational properties of Products in Customer and Customers in Product.
All I want to do is find the product related to a customer pull out some data from both tables namely CustName and ProductName.
The SQL I would use is:
SELECT c.CustName, p.ProductName FROM Customer c
INNER JOIN CustomerProduct cp on c.CustomerId = cp.CustomerId
INNER JOIN Product p on cp.ProductId = p.ProductId
WHERE c.CustomerId=101
I don't know how to use the Addresses navigational property to access the Address data in one query.
You include them and then access them via the property in the Entity class.
Dim query = model.User.Include("Address").Include("UserAddressLink").Where(Function(o) o.UserId = 101).FirstOrDefault
If Not query Is Nothing Then
Dim houseNumber = query.Address.HouseNo 'uses the navigation property
End If
Thanks to InteXX I managed to work it out. This is my whole solution
Using db as new CustProdEntities
Dim query = db.Customers.Include(Function(U) U.Products).ToList
txtCustomer.Text = query.First.CustName
txtProduct.Text query.First.Products.First.ProdName
End Using
The bit I was stuck on was having to filter twice to the Product data. I'm not sure if there's an easier way to do this but it works for now.