T4 doesnt generate KEY when key exists in database view & in EDMX - edmx

We are using EF6.1.1
I have a database view. The view has "ID" column and is not nullable. I added that view on edmx designer. I notice the key icon infront for "ID" column in the designer. When I right click on "ID" column on the designer I also notice "Entity Key" option is selected
But when T4 regenerates entities, I don't see the corresponding entity has "Key" attribute on the ID column.
So I get compile time warning
Warning 4 Error 6002: The table/view 'XXXXXX' does not have a primary key defined. The key has been inferred and the definition was created as a read-only table/view.

In your SqlServer:
CREATE FUNCTION FunctionName() RETURNS TABLE AS RETURN (SELECT * FROM [dbo].[Viewname])
In your app, upgrade your model from database and import function FunctionName.
In your controller:
var some = db.**FunctionName()**.SingleOrDefault(c => c.field == someparam);

Related

django migrate primary OneToOneFiled ForeignKey + into composite foreign key

I've a model which is just a relation between two entities like this:
class SomeModel(models.Model):
a = OneToOneField(User,primary_key=True,...)
b = ForeignKey(Car,...)
As per design, it was correct, as I didn't want an User to have multiple Car. But in my new design, I want to accept multiple Car to an User. So I was trying something like this:
class SomeModel(models.Model):
class Meta:
unique_together = (("a", "b"),)
a = ForeignKey(User,...)
b = ForeignKey(Car,...)
But during migration, it asks me:
You are trying to add a non-nullable field 'id' to somenmodel without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option:
I just wanted to remove that foreign key from OneToOneRelation and add a new id combining both. - How to resolve this?
Delete the model and table from the database and create a new model from starting or add null=True to the given field. you must be having some data (rows) in your table and now you are creating a new column, so previous rows need something to be there in the newly created column, writing null = True will do that.

Postgresql Update JSON Column Retaining Some KeyValues and Adding Additional KeyValue as null

I am trying to use a metadata JSONB column for a multi-tenant application. Every user for each tenant must have the same metadata, but the tenants have varying metadata fields.
In order to keep all user metadata in sync per tenant, when the tenant admin modifies the metadata fields I need to make sure all users have their metadata JSONB column updated with the following criteria:
If the metadata field/key already exists, the value needs to be retained
If the metadata field/key is new, the key needs to added with a null value
If there are any metadata fields/keys that are not included in the updated list, they should be deleted from the JSON object
For example, all the users for Tenant #1 have the following metadata assigned: { "EmployeeNo" : 123, "HireDate" : "2012-10-10", "Age" : 43 } and somewhere down the line the admin decides they don't care about Age, but they do want to start tracking ParkingSpace.
I need the new metadata record to retain the EmployeeNo and HireDate values, remove the Age key/value, and add the ParkingSpace key with a null value. { "EmployeeNo" : 123, "HireDate" : "2012-10-10", "ParkingSpace" : null }.
I would have thought that I could run an update query similar to the following where it returns a JSONB object where it selects the values if the key exists and a null if it doesn't:
UPDATE users SET metadata = metadata[keys: 'EmployeeNo', 'HireDate', 'ParkingSpace'] WHERE tenant_id = 1;
Obviously that won't work, but hopefully it indicates the issue?
Update: I might have misunderstood your question. Maybe you wanted something like that instead:
UPDATE users
SET metadata = (SELECT json_object_agg(n,metadata->>n) FROM unnest(ARRAY['EmployeeNo','HireDate','ParkingSpace']) AS t(n))
This solution involves creating a brand new jsonb object by extracting only the field that you want from the original metadata. The fields to be copied over are specified as an array that you can easily customize.
Original answer: I think this should do it:
UPDATE users
SET metadata = (metadata - 'Age') || '{"ParkingSpace": null}'::jsonb;
I am using the || operator which merges 2 jsonb objects into one and the - operator which removes a key/value pair.

How to increment primary key without using Auto Increment in MySql

I am having a table called Tl which consists of fields ID,Name and Course.
In my view when i click ADD DETAILS button i should be able to fill name and course and save it DB.
Here my ID is primary key.But i am not using AutoIncrement for this field.Without using increment option i should be able to save the newly added values.
Can any one suggest me how to implement this using linq query.
Thanks!
I'll suppose that you're using EntityFramework
var dbMaxId = context.TIs..Max(m => (int?) m.ID);
model.ID = dbMaxId + 1;

Does LINQ to SQL support Single Unit of work only or can I persist the Context and do Next operation?

I have a windows application. I am trying to insert a record through a DataContext. It has Unique identifier in the table. Even I am executing a trigger after insertion. So I am making a select query in the end of the trigger to get the auto generator number and to avoid auto-sync error. As it's a windows application I can keep the Context for longtime. When I create a new object ( for example order) and do the same previous operation, upon SubmitChanges operation, it shows cannot have duplicate key. Why can't I use this same Context to Insert the second record? Or do I need to create a new Context to insert a new Record?(Does this Unit of work Concept comes here?). Creating new Context is bad idea as I need to load all data again..
Any thought?
Some code sample to explain my situation:
CallCenterLogObjCotext = (CallCenterLogObjCotext == null ? (new CallcenterLogContext) : (CallCenterLogObjCotext));
CallDetail newCallDetailsOpenTicket = new CallDetail();
newCallDetailsOpenTicket.CallPurpose = (from callpuposelist in CallCenterLogObjCotext.CallPurposes
where callpuposelist.CallPurposeID == ((CallPurpose)(cbcallpurpose.SelectedItem)).CallPurposeID
select callpuposelist).FirstOrDefault();
Lots of settings like this ...
CallCenterLogObjCotext.CallDetails.InsertOnSubmit(newCallDetailsOpenTicket);
CallCenterLogObjCotext.SubmitChanges();
As I mentioned above, this is a click on Open Ticket button on windows form. I change the values of fname, lname and all in the textboxes available on that form and clicked the same button.
So it will call the same method again. I get the below specified error:
System.Data.Linq.DuplicateKeyException: Cannot add an entity with a key that is already in use.
You can insert more than one row with the same context object, see http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx, http://msdn.microsoft.com/en-us/library/bb425822.aspx, and other numerous online examples. The duplicate key issue could be a linq to sql configuration issue, or a database integrity error, i.e. such as if you have a natural primary key on a table and are trying to insert a row with the same natural primary key more than once.

auto generate in LINQ to SQL

I have a table whit 2 columns , ID and name .I set 'YES' Identity for ID column .
I want to insert data to table whit LINQ .I want to get only name column from user in my application , and then ID column fill automatic to database and I can't give data that column and fill whitout I give it .
What should I do ?
I write in c# and work whit LINQ .
So your database field already is a INT IDENTITY - right?
Next, in your LINQ to SQL designer, you need to make sure your column is set to:
Auto Generated Value = TRUE
Auto-Sync = ON INSERT
Now if you add an entry to your database, the ID will be automatically updated from the value assigned to it by the database:
YourClass instance = new YourClass();
instance.Name = "some name";
YourDataContext.InsertOnSubmit(instance);
YourDataContext.SubmitChanges();
After the SubmitChanges call, your instance.ID should now contain the ID from the database.
If you used the DBML designer, that should be setup correctly.
The 'id' will be populated after you call SubmitChanges.
Make sure your database table is setup correctly and that your ID is set as the primary key field and to auto increment. Regenerate your DBML if you need to by deleting the object and re-adding it. It should know that the ID is not needed and the auto fill it once the insert has succeeded.