LINQ to SQL - linq-to-sql

While trying to use LINQ to SQL I encountered several problems.
I have table persons:
int ID
string firstName
string lastName
And table notes that has:
int ID
string noteText
string createdBy
datetime creationDate
int PersonID
PersonID is a foreign key and the relationship is 1:n
I tried to use LINQ to SQL to create a person and some notes for each person.
Person person = new person();
Person.firstName = "me";
Person.note = new note();
Person.note.noteText = "some text…";
_DataContext.Persons.InsertOnSubmit(person);
_DataContext.SubmitChanges();
The problem is that the person object doesn't yet exist in the DB so it doesn't have an ID yet. So the note.personID filed has a 0 value… (the ID field is an identity field in the sql server)
The only solution for this that I found is to create a person , submitchanges and then create a note and submitchanges again.
Am I missing something here or maybe that’s the way one should work with LINQ to SQL?
How can I add multiple notes per person with LTS? I have a 1:n relationship and I don't see it with LTS.
If a person has 10000 notes, I don't want the person object constructor to load all the notes he has. I want to load them only when I refer to them. How can I config LTS to load the notes on demand?

If you aren't using the LinqToSql class designer, you should think about using it. The classes it generates will support the insertion scenario you outlined.
I can tell you aren't using the designer because it would give you a Notes (plural) property on the Person... as Person is 1 to Many with Notes.
How can I config LTS to load the notes on demand?
The designer will generate a property of type EntitySet(Note), which will load Notes on demand.

Related

Entity Framework does not keep JSON data Id

I am new to ASP.NET MVC, especially Entity Framework.
I am trying to save JSON data from external service to SQL server. I use Code First and it creates tables and inserts all records. But original ID values are changed to SQL auto generated ID value. For example, original ID 20050 become 1. Please check attached photos. I googled my problem and did not find a solution.
This is my fist time posting a question in stackoverflow too. Thanks in Advance.
you can set identity specification to false to that table usine DataAnnotations attribute.
[DatabaseGenerated(DatabaseGeneratedOption.None)];
public int ID { get; set; }
Than apply migration.

How to get records with last dates in Django ORM(MySQL)?

I have models:
class Reference(models.Model):
name = models.CharField(max_length=50)
class Search(models.Model):
reference = models.ForeignKey(Reference)
update_time = models.DateTimeField(auto_now_add=True)
I have an instance of Reference and i need to get all last searches for the reference. Now i am doing it in this way:
record = Search.objects.filter(reference=reference)\
.aggregate(max_date=Max('update_time'))
if record:
update_time = record['max_date']
searches = reference.search_set.filter(update_time=self.update_time)
It is not a big deal to use 2 queries except the one but what if i need to get last searches for each reference on a page? I would have got 2x(count of references) queries and it would not be good.
I was trying to use this solution https://stackoverflow.com/a/9838438/293962 but it didn't work with filter by reference
You probably want to use the latest method.
From the docs, "Returns the latest object in the table, by date, using the field_name provided as the date field."
https://docs.djangoproject.com/en/1.8/ref/models/querysets/#latest
so your query would be
Search.objects.filter(reference=reference).latest('update_time')
I implemented a snippet from someone in gist but I don't remember the user neither have the link.
A bit of context:
I have a model named Medicion that contains the register of mensuration of a machine, machines are created in a model instance of Equipo, Medicion instances have besides of a Foreign key to Equipo, a foreign key to Odometro, this model serves as a kind of clock or metre, that's why when I want to retrieve data (measurements aka instances of Medicion model) for a certain machine, I need to indicate the clock as well, otherwise it would retrieve me a lot of messy and unreadable data.
Here is my implementation:
First I retrieve the last dates:
ult_fechas_reg = Medicion.objects.values('odometro').annotate(max_fecha=Max('fecha')).order_by()
Then I instance an Q object:
mega_statement = Q() # This works as 'AND' Sql Statement
Then looping in every date retrieved in the queryset(annotation) and establishing the Q statement:
for r in ult_fechas_reg:
mega_statement |= (Q(odometro__exact=r['odometro']) & Q(fecha=r['max_fecha']))
Finally passed this mega statement to the queryset that pursues to retrieve the last record of a model filtered by two fields:
resultados = Medicion.objects.filter(mega_query).filter(
equipo=equipo,
odometro__in=lista_odometros).order_by('odometro', 'fecha') # lista_odometros is a python list containing pks of another model, don't worry about it.

To fetch column name

I am using struts2 , hibernate and MySql for my project.
I have table name TimeTable having 42 columns (all long datatype) containing course codes.
I want to search "column names" having particular course code from a particular row.
Help me please.
If you have mapped the entity in a "proper" way in hibernate, the answer is obvious:
You will have an entity called TimeTable, which have 42 relationships to Course (I bet the attribute name will be course1, course2.... course42).
The resulting HQL is simply a bunch of OR
from TimeTable t
where t.course1.code = :something
OR t.course2.code = :something .....
However, it is obviously a bad model design. You should make Timetable and Course a Many-To-Many relationship, and have another table storing the relationship. So, in the entity, you will see something like
class TimeTable {
#ManyToMany
private List<Course> courses;
}
Your life will be much easier with such design.

How to implement lookup table in mvc framework?

Asp.net MVC2: I have many dropdownlists in my mvc application. At first, I started by creating a table for each one with a unique ID and name and referring to them in the controllers and views. The application got bigger, and it was suggested that I use a lookup table, that contains lookuptype and lookupvalue as compound primary key and fill all the values for the dropdownlists in it. I've looked all over the internet, the only method used for mvc is one table for each dropdownlist! Can someone explain to me how I can implement it, and in detail please becoz I'm totally lost. A link to a tutorial would also be great.
I'm using vb.net and linq to sql.
Suppose your tables have columns ID, Name and Value. Now by having only one table that table would most probably look like this:
create table Lookup
(
LookupID int not null identity
primary key,
LookupTypeID int not null
references LookupType(LookupTypeID),
Name nvarchar(50) not null,
Value int not null,
unique(EnumTypeID, Name)
)
go
This table will make sure that within the same type names don't clash.
Anyway. You could of course have a similar application (not data) model class
public class EnumValue
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int Value { get; set; }
}
So whenever you get values of a certain type you can always generate an IList<EnumValue> of them and feed them to a particular drop down.
Since you didn't provide any valuable data this table and class could omit column/property Value, because depending on the inner workings it may not be needed at all. But you will know this best because you know your application requirements. Instead of this column/property only ID could do the trick.
I actually used a slightly different approach. I created a table that has a composite primary key, LookupName and LookupValue. Then in the datacontext I declared a method that takes the lookupname as a parameter, and then brings a list of lookupvalues whose lookupname match this parameter. In the original table (ex.Contact) I created a field called status, where the selected value will be saved. Then in the controller, I used viewdata to create dropdownlists.
Example: _db represents the datacontext
Viewdata('Status')= new selectlist(_db.Getlookupname('status'),'lookupname','lookupname')
and then in the view
html.dropdownlist('status')
I also named the dropdownlist with the same fieldname 'status' that is found in the target table 'Contact'.
And it worked, without any complexity or errors.
Thanks for the help. And I hope this will be helpful to someone else!
Here's a sort of tutorial on how to achieve a generic lookup service.
http://wtfperminute.blogspot.com/2011/02/working-with-reference-data-lookups.html
Similar to what you've done, but perhaps a bit more comprehensive.

Linq to SQL - Error handling

I have a linq to sql statement that inserts records in the database. If there is a duplicate, it throws Primary key violation .
after this happens, whenever i try to execute any other statement, it repeatedly shows this error. Is this a problem of transaction not getting closed. Also how to handle transactions in a more reliable way in LINQ to SQL
Each DataContext instance tracks the instances of the mapping classes that it has seen. When you say: myDataContext.InsertOnSubmit(myCustomer); you are registering a customer instance with this DataContext. Later, when you say myDataContext.SubmitChanges();, the DataContext attempts to carry out all changes that it is tracking.
If these changes fail - the DataContext does not stop tracking them and will attempt to make the change each time SubmitChanges is called.
In order to have a DataContext that is not tracking a record that it can't insert, you should abandon this instance and new-up another one.
If your primary key field is an identity field, DO NOT populate it when you insert it into the database. For example, given a Customer table with the following structure:
Customer
========
Customer_ID (PK, identity)
Last_Name (varchar)
First_Name (varchar)
Middle_Initial (char)
this is possible:
public int CreateCustomer(string lastName, string firstName, string middleInitial)
{
using (DataContext dc = new DataContext())
{
Customer customer = new Customer();
customer.Last_Name = lastName;
customer.First_Name = firstName;
customer.Middle_Initial = middleInitial;
dc.Customers.InsertOnSubmit(customer);
dc.SubmitChanges();
return customer.Customer_ID;
}
}
The most likely reason for your error is that you are trying to access the entity object after the DataContext in which it was created has been destroyed. Using the above example, this will produce an error similar to the one you are probably receiving:
public int CreateCustomer(string lastName, string firstName, string middleInitial)
{
using (DataContext dc = new DataContext())
{
Customer customer = new Customer();
customer.Last_Name = lastName;
customer.First_Name = firstName;
customer.Middle_Initial = middleInitial;
dc.Customers.InsertOnSubmit(customer);
dc.SubmitChanges();
}
return customer.Customer_ID; // <<-- Error occurs here
}
The reason the error occurs is due to the built-in change tracking of the LINQ engine. When the DataContext is created, any entity objects created within that DataContext are tied to that DataContext via a reference within the entity object. Once the DataContext falls out of scope, the reference is no longer valid and the contents of the entity object are no longer considered reliable to the LINQ engine.
As far as transaction handling is concerned, a transaction is created when the DataContext is created. When SubmitChanges is called, all changes are executed within the context of the DataContext's transaction, no matter how many entities/tables are involved.
Are you re-using the same DataContext? If so, don't do that - create a new DataContext for each logical operation and use TransactionScope to manage transactions
Why not check for a duplicate record before trying to save the record?
Throwing exceptions are very costly.