Saving Data to Relational Database (Entity Framework) - database

I'm having a little bit of trouble saving data to a database. Basically, I have a main table that has associations to other tables (Example Below).
Tbl_Listing
ID
UserID - Associated to ID in User Table
CategoryID - Associated to ID in Category Table
LevelID - Associated to ID in Level Table.
Name
Address
Normally, it's easy for me to add data to the DB (using Entity Framework). However, I'm not sure how to add data to the fields with associations. The numerous ID fields just need to hold an int value that corresponds with the ID in the associated table.
For example; when I try to access the column in the following manner I get a "Object reference not set to an instance of an object." error.
Listing NewListing = new Listing();
NewListing.Tbl_User.ID = 1;
NewListing.Tbl_Category.ID = 2;
...
DBEntities.AddToListingSet(NewListing);
DBEntities.SaveChanges();
I am using NewListing.Tbl_User.ID instead of NewListing.UserID because the UserID field is not available through intellisense.
If I try and create an object for each related field I get a "The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects." error.
With this method, I am trying to add the object without the .ID shown above - example NewListing.User = UserObject.
I know this should be simple as I just want to reference the ID from the associated table in the main Listing's table. Any help would be greatly appreciated.
Thanks in advance,
-S

In general, with Entity Framework you don't use the ID:s of foreign keys, instead you use references. Instead of setting the ID, you set the property of the associated table.
In your case, it would be something like this:
Listing newListing = new Listing();
newListing.Tbl_User = DBEntities.Users.Single(u=>u.ID == 1);
newListing.Tbl_Category = DBEntities.Categories.Single(c=>c.ID == 2);
...
DBEntities.AddToListingSet(newListing);
DBEntities.SaveChanges();
In Entity Framework 4 (coming with .NET 4.0) you'll be able to use a simpler syntax more like what you expected.
You can have a look at this article on msdn where you can read more about this!

Related

Create adhoc page relationship through kentico api when using pages data type

We can add page relationship in two different ways using named relationships and pages data type which is kind of advanced content modelling in Kentico..
if we go through named relationships then we can give a meaningful relationship between to content node by providing description. So, we get a relationship name called “is related to”(example). When we use this in practice, then we get [page A] {is related to} [Page B].
if we go through pages data type then we assign some content on the form tab, records are created in the “CMS_Relationship” table as ad-hoc via the “RelationshipIsAdHoc” column and there is no relationship name for this as such. It is marked as Ad-hoc. and Relationship name is also added page type name underscore some randon guid example abc.product_3d628a37-7637-4a21-b0b4-e1dd1a00a3bc
My question is when we try to use page data type and we need to add relationship through api code, then how can we add because in kentico api to add page relationship through api code RelationShipNameID is mandatory field. We don't have this RelationShipNameID as we are not going through named relationship.
Found out the way
Need to retrieve ad-hoc relatioshipnameinfo object, e.g. like this:
string codeName = GetAdHocRelationshipNameCodeName("fillclassnamehere", field);
var relationshipNameInfo = GetRelationshipNameInfo(codeName);
and then use is with API:
RelationshipInfoProvider.AddRelationship(leftSiteId, rightSiteId, relationshipNameInfo.RelationshipNameId)

Are content types in Drupal 8 the same as tables in a database?

If I am creating a database and I have two tables with a many-to-many relationship, I would create a third table to represent the relationship.
But how should I implement the above data model in Drupal 8, should I create three content types? so my question is, are content types in Drupal 8 the same as tables in a database, or are they something else that should be used in a different way?
To store data in a custom table in Drupal 8 you're going to want to define a custom schema and expose it through a hook. Here is Acquia's documentation on that process. This is not the same as creating a content type.
Content type data is stored across several tables that are shared by other content types (such as node and node_revision) and manipulating these tables is not easy.
The quickest way to add a content type is through the method recommended in Adding a Content Type from chapter 6 of the Drupal 8 User Guide. This allows for all the standard GUI methods for manipulating data structures.
As Isaiah says, content types in Drupal are not technically the same as tables in a database as they use many tables. But!
In your case, if you have something like table A with:
- name
- email
- phone
- id
And a second table, table B with:
- company
- something else
- etc…
- id
and are looking at a third that would likely be something like:
- id
- table A id
- table B id
Then the answer is yes.
In this case you would have content type A with fields for name, email, phone, and then an entity reference field pointing to content type B with the company fields.
You can reference in any direction with the entity reference field.
You might also find "Is there a way to input the data of multiple content types" helpful.

How to change GUID of entity before saving back to database (in C#)

We have code to serialize entities to file:
formatter.Serialize(fileStream, session); // BinaryFormatter
and to deserialize:
session = (Session)binaryFormatter.Deserialize(innerStream);
The entity structure is quite complicated and if necessary I can come up with a simpler example, however the crux of the problem is this. There is a Patient table that has multiple "Sessions". The Patient has an associated table "Cities", and therein lies the problems. Each computer has it's own Database (SQLServer Express) and has a table Cities which contain exactly the same data (London, Madrid, Berlin). However, on each machine, the unique key for the city (a GUID) is different! When I deserialize a session on another machine from which it was serialized on, I want to use the same city based on name, NOT Guid.
The deserialization works fine. It's the deserialized entity to the database that causes me grief. To get the City GUID correct, I use:
session.Patient.City.CityGUID = tempCity.CityGUID;
session.Patient.CityGUID = tempCity.CityGUID;
tempCity is the entity from the database with the matching name (like 'London').
I can do this, but on the line:
context.Patients.Attach(session.Patient);
I get an exception of the form:
[System.InvalidOperationException] = {System.InvalidOperationException: The property 'CityGUID' is part of the object's key information and cannot be modified.
at System.Data.Entity.Core.Objects.EntityEntry.DetectChangesInProperty(Int32 ordinal, Boolean detectOnlyComplexProperties, Boolea...
Any ideas on how to fix this? I can create whole new objects but this is problematic because if I deserialize two sessions that both have the same patient, they should remain that way in the new database. My creating new entities, I end up with 2 new patients.
I think the best solution is to make sure the Cities have the same GUIDs on different machines, perhaps by modifying the install set, but I'm wondering if there is a simple fix.
Opinions?
Dave
In fact, I need to replace the entire entity: session.Patient.City = tempCity;

Cakephp inherited tables

I have the following situation with three tables, which are inherited from
contactBasics
contactSales (foreign key of contactBasics)
contactSupporters (foreign key of contactBasics)
The general data about a person is stored in contactBasics
Specific data about Sales People are additionally stored in contactSales
Specific data about Supporting People are additionally stored in contactSupporters
Is there a good way to handle e.g. contactBasics and contactSales as one object in code ?
help appreciated.
Endo
Assuming there is very similar data between contactSales and contactSupporters, you could just to have a 'contacts' table and add a contact_type field that clarifies which type of contact it is.
This also allows you to expand should you ever need another contact type.
You can use a short string field and have it be 'sales' or 'supporter', or you can go with an int field and have 1 = sales, 2 = supporter...etc. Which of those is up to your preference and app needs.
You can still keep both models if you want/need. In your associations, you can add conditions to differentiate between the two.
(or here for cake 3)

Many-to-Many relationship in Zend 2 Framework

I use the Zend 2 Framework to build my web application. I implemented my database table models by this tutorial: http://framework.zend.com/manual/2.1/en/user-guide/database-and-models.html
I have a many-to-many relationship between two models in my database. To get data from them I googled and found this link: http://mattmccormick.ca/2010/04/24/how-to-easily-create-models-and-table-relationships-in-zend-framework/
The problem is that all the table models extends from Zend_Db_Table_Abstract in the example. I don't know how to get data from the models.
I have a table containing votings, every voting has a unique hash id. Every voting also has tags. Therefore I defined a table tags with all the tags available and a voting_tag_map where all many-to-many relationships are mapped.
What I have tried so far is the following, that's code from my VotingTable class:
public function getTagsByVoting($votingHash){
$select = $this->tableGateway->getSql()->select();
$select->from(array('v' => 'voting'))
->join('voting_tag_map', 'v.voting_id=voting_tag_map.voting_id')
->join('tags', 'voting_tag_map.tag_id=tags.tag_id');
$resultSet = $this->tableGateway->selectWith($select);
return $resultSet;
}
It says then:
Since this object was created with a table and/or schema in the constructor, it is read only.
Thats because of the from() method. If I delete the from() method, it says:
Statement could not be executed
Can anyone help me please?
Since this object was created with a table and/or schema in the constructor, it is read only.
This error is because you are trying to set the table name in the from clause, but it's already been set in the contructor of the TableGateway, and you can't change it once set.
If you really need to do this then you can extens AbstractTableGateway yourself then you won't have to add a string tablename to the contructor, but you don't really need to use an alias on your main table...
The SQL error you get when you comment out the from() method will be due to your referencing the votes table as it's alias 'v' in your join, when you are not using the alias v, try changing it to 'voting.XXX' from 'v.XXX'

Resources