How to get primary key field name for null EntityReference? - entity-framework-4

I've made the following function to assign value to a foreign key reference (I know, it's dirty and does not work for compound keys):
void setFk(dynamic tbl,object id){
var path=db.DefaultContainerName+"."+tbl.TargetRoleName;
var ret=new System.Data.EntityKey(path, tbl.RelationshipSet.ElementType.RelationshipEndMembers[0].GetEntityType().KeyMembers[0].Name, id);
tbl.EntityKey=ret;
}
which I want to invoke by this: setFk(newRec.WorkItemsReference,src.WorkItemsId)
The problem is that it does not work for newly created object newRec because tbl.EntityKey and tbl.RelationshipSet are both null.
One route that I see is to get tbl.GetType() and somehow locate Id column from there. If this is the right route then how ?
Any other route ?
My goal was not to pass more arguments into setFk function because it's supposed to be sufficient with 2 arguments and would lead to duplication of entity name.

Related

asp.net mvc4 controller allow null complex object

If I have this:
public ActionResult BuscarClientes(SomeClass c)
{ ... code ...}
And I access the url to this action without any parameter (so I don't give any elements to my model), I still get a newly created object. But, I'm wanting to get a NULL object instead if no arguments are given.
This is because I'm using this method as a search action method, and the first time the get is done I don't want to perform any validation and just return the view. After that, the post will be a GET method (its a search I need to make it a get request) with all the values in the query string.
How can I force the model binder to give me a null object if no parameters are given in the query string? Because as it is now, i get a new instance of SomeClass with all its properties set to null. Instead of just a null object.
Try specifying default value to the parameter
public ActionResult BuscarClientes(SomeClass c = null)
{ ... code ...}

Websecurity.CreateUserAndAccount on Azure doesn't work

I have a method that registers a new user using WebSecurity.CreateUserAndAccount(model.UserName, model.Password) The problem is that in the UserProfile model I have added a GUID Key. On my local machine this just populates an empty Guid when I call this method. On azure however, I get the following error:
System.Data.SqlClient.SqlException (0x80131904): Cannot insert the value NULL into column 'Key', table 'Scheduler.dbo.UserProfile'; column does not allow nulls. INSERT fails.
Now, I've tried to generate a new GUID in the constructor of the model, manually have the Set{} generate a new GUID and I get the same error.
When I try to use the CreateUserAndAccount overload like:
WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Key = Guid.NewGuid() });
I get the following syntax error (run time):
Incorrect syntax near the keyword 'Key'.
I've spent a good part of the morning trying to figure this out and I just can't. By the way all of the above methods still result in an empty GUID 00000000-0000-0000-0000-000000000000 and the overload gives me syntax error on my local machine.
"Key" is a reserved word in SQL, it should be used in brackets like this [Key]
Since you don't have control on how WebSecurity generate the SQL query then your only option is to rename it to something like UserKey

Error in breeze using EF 5 and calling stored procedure

Getting an error client side with breeze: "Cannot call method 'map' of undefined" when trying to pull over some data. The difference between this action and one that works is that this action is calling a stored procedure and returning ObjectResult<T> instead of DbSet<T>.
Might this be why I get an error? Using Chrome Developer tools, I do see that the breeze controller is returning json data.
I have created a complex model type in the edmx for mapping the rows returned from the stored procedure.
The action in the breeze controller has a return type of IEnumerable<T>.
I experienced the same error when using an EF complex type. A workaround was to create a view in my database instead of using a complex type, set the stored procedure to return a type of the new view which had a primary key and then it worked. It would seem that breeze requires entities to have a primary key defined.
Hm... not quite sure what is happening, so just guessing here, but try adding an AsQueryable() to the result returned, and changing the result type to a IQueryable.
We don't have any stored proc tests for breeze yet, but this is impetus for me to add some :)
I had the very same issue, but thank God I figured out a solution. Instead of using a stored procedure, you should use a view, as Breeze recognizes views as DbSet<T>, just like tables. Say you have a SQL server table that contains two tables Customers and Orders.
Customers (**CustomerId**, FirstName, LastName)
Orders (OrderId, #CustomerId, OrderDate, OrderTotal)
Now, say you want a query that returns orders by CustomerId. Usually, you would do that in a stored procedure, but as I said, you need to use a view instead. So the query will look like this in the view.
Select o.OrderId, c.CustomerId, o.OrderDate, o.OrderTotal
from dbo.Orders o inner join dbo.Customers c on c.CustomerId = o.CustomerId
Notice there is no filtering (where ...). So:
i. Create a [general] view that includes the filtering key(s) and name it, say, OrdersByCustomers
ii. Add the OrdersByCustomers view to the entity model in your VS project
iii. Add the entity to the Breeze controller, as such:
public IQueryable<OrdersByCustomers> OrdersByCustomerId(int id)
{
return _contextProvider.Context.OrdersByCustomers
.Where(r => r.CustomerId == id);
}
Notice the .Where(r => r.CustomerId == id) filter. We could do it in the data service file, but because we want the user to see only his personal data, we need to filter from the server so it only returns his data.
iv. Now, that the entity is set in the controller, you may invoke it in the data service file, as such:
var getOrdersByCustomerId = function(orderObservable, id)
{
var query = breeze.EntityQuery.from('OrdersByCustomerId')
.WithParameters({ CustomerId: id });
return manager.executeQuery(query)
.then(function(data) {
if (orderObservable) orderObservable(data.results);
}
.fail(function(e) {
logError('Retrieve Data Failed');
}
}
v. You probably know what to do next from here.
Hope it helps.

Insert fails on Code First whith non-identity id key

I have defined a model class with an ID column set as [Key], on an existing database table. the table has the field defined as primary key, int, not null. It is NOT and identity column.
When creating a new record in code, I am setting the ID column (to an unique value) in code before calling the SaveChanges() method.
The method returns with the error:
Cannot insert the value NULL into column 'xxx_id', table
'xxx.dbo.xxxxxx'; column does not allow nulls. INSERT fails. The
statement has been terminated.
It seems that EF assumes that the ID column is an Identity column and therefore doesn't pass the ID in the SQL call to the database.
Is there a way to define the ID column to tell EF that is it not an Identity column and to pass the value in the SQL call
You need to specify the DatabaseGeneratedOption for the property. In this case, the DatabaseGeneratedOption should be None.
See: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.databasegeneratedoption%28v=vs.103%29.aspx
I have usually done this with fluent coniguration like:
Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
.. but it looks like this can also be specified with an attribute. See http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.databasegeneratedoption%28v=vs.103%29.aspx
[DatabaseGenerated(DatabaseGeneratedOption.None)]

Url.RouteUrl returns null

I'm buiding a UrlHelper for a route
as in best practices
the problem is that the returned value is always null
when debugging in found that
Url.RouteUrl("x") return null
Url.RouteCollection["X"] return Route
i'm trying to do :
public static string Category(this UrlHelper helper, int Id, string category)
{
return helper.RouteUrl("X", new {id = Id, category= category});
}
I can't see where I'm doing something wrong
It appears that this is being caused because you did not specify a default value for {id} and {category} when registering your routes.
Url.RouteUrl("x") will return null because there's no value for id and category provided, and your route definition does not have a default.
I think that you will find if you update your route entry to specify a default value for id and category this will solve your problem. Alternatively, if you are sure to always provide a value for id and category, you can do without it.
As far as your actual Url helper method Category(), that should be working just fine as-is if you are providing a non-null or empty value for id and category. I literally copied the code and it works for me.
For some reason i was still running the mvc release candidate
I installed the mvc 1.0 and now it works fine

Resources