counting table rows in mvc view - asp.net-mvc

I am counting table rows in MVC view.
The below code was counting from a linked table but has now stoped giving me the following error:
Object reference not set to an instance of an object.
Has anyone any idea as to why this would happen?
#Model.Count(x => x.Device.VehicleReg != null)

You Device is null and throws exception
Try this:
#Model.Where(x=> x.Device != null).Count(x=> x.Device.VehicleReg)

Assuming that Model is not null, probably Device is null that's why you get the "Object reference " error

Related

Navigation with OData properties

I want to use a table for navigation purposes. Therefore I use the following code (the table looks good, all datas are complete):
// Admin.view.xml View
<Table id="objectsTable" itemPress="onSelectionChange">
// Admin.controller.js Controller
onSelectionChange: function(event) {
// After call undefined
var partnerId = event.getSource().getBindingContext().getProperty("BUSINESS_PARTNER_ID");
// After call defined and correct
var objectId = event.getSource().getBindingContext().getProperty("ID");
var router = this.getOwnerComponent()
.getRouter();
router.navTo("adminDetails", {
partner: partnerId,
object: objectId
});
After debugging I found out, that the value objectIdis undefined (while ID is present). This causes the navigation to not work properly.
So I looked at the data source (oData), which looks as follows :
ID | BUSINESS_PARTNER_ID | ADDRESS | FILES (oData association/navigation) |
.... All records are available, including the BUSINESS_PARTNER_ID
Why is the variable BUSINESS_PARTNER_IDundefined while all the data from the records are displayed correctly? I can query it, except BUSINESS_PARTNER_ID. Does anybody know how I can fix this?
Do partnerId and objectId have values? If the values for these are there then we need to check the routing and your manifest files. If partnerId and ObjectId are blank.
If these fields are blank i can think of another fix. Instead of binding the event from table, i believe you must have a columnlistitem or objectlistitem under your table. You can assign the press event on that and move this code to that.
Basically i am triggering the event from list item instead of table.
Thanks and Regards,
Veera
"Just" change my query to
event.getParameter("listItem").getBindingContext().getProperty("XYZ");

Attempt to index field 'wikibase' (a nil value)

I have imported to my MediaWiki site the it.Wikipedia Modulo:Bio but I get this error:
Error Lua in Module:Bio line 700: attempt to index field 'wikibase' (a nil value).
In line 700 I have this code:
local entity = mw.wikibase.getEntityObject()
I have multiple wikis that shares the same source code, and the same database, but with its own tables. Then my wikibase is mybase.mywiki.com.
I tried to solve by changing wikibase to mybase:
local entity = mw.mybase.getEntityObject()
But it doesn't work.
The problem is not wikibase: the error simply says that there is no field named wikibase in the mw table, so the problem is that mw doesn't contain what you think it should. You must find the code that puts wikibase field in mw. If it does something like mw.wikibase = something and something is nil, then it is as if that line had not executed (it is not an error to assign nil to a table field, it is like removing the field if it exists already, and doing nothing if it doesn't exist). This is common error when something is an function call, the function may return nil under some circumstances.

Activity Log is not Inserted in Nopcommerce

I am using Nopcommerce 2.65.
I have created new page at admin side of Nopcommerce.
Now I am trying to add Log of that page in Activity Log.
but In Activity log Record is not Inserted because in Insert method it finds Systemkeyword and it found NULL
I am calling Insert Activity Method Like:
_customerActivityService.InsertActivity("AddNewQuote", _localizationService.GetResource("Custom.ActivityLog.AddQuote"), quote.Id);
At Definition side of InsertActivityLog
var activityType = activityTypes.ToList().Find(at => at.SystemKeyword == systemKeyword);
if (activityType == null || !activityType.Enabled)
return null;
Please Suggest
You have to add the activity type record with this system name "AddNewQuote" to the [ActivityLogType] table

The member with identity ' ' does not exist in the metadata collection.\r\nParameter name: identity

I simplified the code a little while trying to debug:
[HttpPost]
public ActionResult Register(User model)
{
DateTime bla = new DateTime(2012, 12, 12);
try
{
User user = new User
{
gid = 1,
cid = 1,
firstName = model.firstName,
lastName = model.lastName,
email = model.email,
username = model.username,
password = model.password,
creationDate = bla,
active = 1
};
myContext.Users.AddObject(user);
myContext.SaveChanges();
}
catch (Exception ex)
{
throw ex;
}
return View();
}
The values are transmited accordingly. Users table:
[id] [int] IDENTITY(1,1) NOT NULL,
[cid] [int] NULL,
[gid] [int] NULL,
[firstName] [nvarchar](100) NOT NULL,
[lastName] [nvarchar](100) NOT NULL,
[email] [nvarchar](max) NOT NULL,
[username] [nvarchar](100) NOT NULL,
[password] [nvarchar](100) NOT NULL,
[creationDate] [datetime] NOT NULL,
[active] [int] NOT NULL,
CONSTRAINT [PK_Users_3213E83F0AD2A005] PRIMARY KEY CLUSTERED
I deleted all the foreign keys to be sure that nothing affects it. I am qute certain that at a previous moment it was working, but now I can not figure where the issue is.
It crashes while performing the savechanges:
{"An error occurred while updating the entries. See the inner exception for details."}
{"The member with identity '' does not exist in the metadata collection.\r\nParameter name: identity"}
I had the same error being thrown when I try to insert using EF, the error was
The member with identity 'Id' does not exist in the metadata collection.\r\nParameter name: identity
It wasn't obvious at first but the exception message was very concise because my database knows the column Id int but the property created for the object on my code was int ID so coming back to named mapping, Id is not mapped to ID.
So when an object with property ID is sent to database that only know Id you will get the above error.
I hope this helps, thanks
The issue was reproducing because of a trigger that was on the users table. Removed it and the issue is not reproducing anymore.
There is probably a trigger on the table being updated and it returns output. The output is thrown away but it conflicts with EF. Such output is often used to debug triggers (and forgotten to delete later):
select 'trigger called, i am here'
or there can be missing variable:
select column
instead of
select #variable=column
I think that the best solution is in this post. I used the 3rd option and works.
Here I report the reply in the link:
The issue could be related to a "instead of insert" trigger on one of
your tables.
The EF framework is performing validation on the inserted row of data
by calling scope_identity(). However, an "instead of insert" trigger
will change the context of the insertion in such a way that the EF
system's call to scope_identity will return null.
A couple ways around this:
Use a stored procedure to insert the data ( not tested )
Remove the instead of insert trigger ( triggers can cause other problems, so some people argue not to use them) ( tested, works!)
Turn off validation in the EF framework, so: context.Configuration.ValidateOnSaveEnabled = false ( tested, works!)
I had this same error today and spent a few frustrating hours trying to figure it out.
I was using Entity Framework to insert a record with an identity column into a SQL server database table. Simple enough.
The table had a trigger on it which in turn ran a stored procedure. The stored procedure had a line in it:
select newid()
This is the line that broke Entity Framework.
For tables with identity columns, Entity Framework expects to be returned a single row with a single field that is the identity column.
it's because of trigger pass back value to EF
if you are using trigger. in my problem i must check a value by selecting from other table and using of 'select' cause error in EF, so you must replace 'select' with 'set'.
you can not use this code.
select #any= any from tablename
you should use set instead of select
set #any= (select any from tablename)
Somedays, I hate M$.
The member with identity 'ChangeID' does not exist in the metadata collection.
Parameter name: identity
I've spent two days trying to get around this.
I'm using MVC.
To get all the data I need in one fell swoop, I created a view of the table in the DB for this application, and tables in other databases. (You may update views, with some constraints.)
I do a get, and all my data is present in the record, keys, descriptions, foreign keys, etc.
I created triggers on my view, to update the portion of the view that came from the local table.
Instead of Delete worked fine.
Instead of Update worked fine.
This error kept raising it's head on Instead of Insert. I could NOT get the insert trigger to successfully insert into my table. If I ran an insert on the view, with all fields provided in the SQL Management Studio, it worked fine. I know the exact values being passed because I ran SQL Server Profiler to see the code being passed.
But when the app attempted the update, it failed with The member with identity 'ChangeID' does not exist in the metadata collection.
Clue up above, someone said, "MVC expects table key to be ID"
I renamed ChangeID as ID in my view, changed it in the App, and BAM! Now it works.
What did NOT work:
db.Configuration.ValidateOnSaveEnabled = false;
adding a select to the trigger to get scope identity
Why do I have to modify my DB or my view to satisfy some hidden M$ assumption?
None the less, after two very frustrating days, code is now working. Maybe this will save someone else some time as well.
Try this
[HttpPost]
public ActionResult Register(User model)
{
DateTime bla = new DateTime(2012, 12, 12);
try
{
model.gid = 1;
model.cid = 1;
model.creationDate = bla;
model.active = 1;
myContext.Users.AddObject(model);
myContext.SaveChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex);
throw;
}
return View();
}
I was having this issue and my fix, was that in my connection-string metadata I did not specify my model in the .msl format.
See more info here
In my case, SetName of the entity was incorrect. Shortly, this worked for me:
Use
myContext.AddObject(nameOfSetEntity, user);
Instead of:
myContext.Users.AddObject(user);
To get the whole correct name of the entity (thanks to Nix's answer)
string className = typeof(User).Name;
var container = myContext.MetadataWorkspace.GetEntityContainer(myContext.DefaultContainerName, System.Data.Metadata.Edm.DataSpace.CSpace);
string nameOfSetEntity= (from meta in container.BaseEntitySets
where meta.ElementType.Name == className
select meta.Name).First();
Context.AddObject(nameOfSetEntity, user);

Cannot insert duplicate key

I am getting this error ...
Violation of PRIMARY KEY constraint 'PK_Members'. Cannot insert duplicate key in object 'dbo.Members'.
The statement has been terminated.
When I try to use the Membership and Role Providers in ASP.NET MVC. It happens when calling the GetUser method from inside the RoleProvider.
var member = System.Web.Security.Membership.GetUser(email) as Models.Member;
//var member = (
// from m in DataContext.Members
// where m.Email == email
// select m).Single();
var role = (
from r in DataContext.Roles
where r.Name == roleName
select r).Single();
member.Groups.Add(new Models.Group(role));
DataContext.SubmitChanges();
It looks like the problem is in the code
member.Groups.Add(new Models.Group(role));
Based on the error message returned by the sql, Read operation like GetUser won't throw this type of error.
I suspect it's because you are adding a group that exists already.
Maybe you should check for the existance of the role before trying to add it.
Hope this helps.
A good way to debug this is to use SQL profiler to determine what SQL code is being run against the database.
I would suspect you are trying to save a record somewhere that has the same primary key already in the database.
SQL Profiler = http://msdn.microsoft.com/en-us/library/ms181091.aspx
Are you sure you are not trying to enter a number into the PRIMARY KEY field that is already there? If it is auto_increment, just enter 0 and it will make the value of that field, the last number+1
Hope this helps :)
If the exception is an SqlException you might get its error number for duplicate records which is 2627. You might catch the exception and verify it and display and manage any error accordingly. I Hope this helps.
catch (SqlException ex)
{
if (ex.Number == 2627)
{
MessageBox.Show("This record exists: "+ex.Message, "Error");
}
else
{
MessageBox.Show(ex.Message, "Error")
}
}
I am a newbie at this but I am going to give this a try, sorry if it doesn't work for you.
I think that instead of using,
member.Groups.Add(new Models.Group(role));
You should use the following (if you are updating the database):
member.Groups.Entry(new Models.Group(role));
And if the above code doesn't work, try this (if you are adding to the database):
// First, search for the particular obj you want to insert
var checkModels = member.Groups.Find(new Models.Groups(roles));
// If the obj doesn't already exist, add it to the database
if(checkModels == null){
member.Groups.Add(new Models.Group(role));
}
// If the obj does exist already, then update it
else{
member.Groups.Entry(new Models.Group(role)).State = EntityState.Modified;
}

Resources