SQLite; "Cannot add a PRIMARY KEY column"-Exception - c#

today I have started coping with databases. I've installed SQLite and SQLite-net. I am Programming a Windows 8.1 App using C#.
All I have is the following:
A Model:
public class Subject
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
}
And the OnLaunched-Event in App.Xaml.cs contains:
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
[...]
// Get a reference to the SQLite database
DBPath = Path.Combine(
Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Subjects.s3db");
// Initialize the database if necessary
using (var db = new SQLite.SQLiteConnection(DBPath))
{
// Create the tables if they don't exist
db.CreateTable<Subject>();
}
[...]
}
When I launch this I get the following error after db.CreateTable(); is executed:
Cannot add a PRIMARY KEY column.
What is going wrong here? I really would appreciate your help.
Thank you very much.
Greetings, FunkyPeanut

I believe this is happening because you've changed the schema of the DB table by adding or removing a field from your Subject class. I.e. you've added the Id property after having already run the application to create the Subject table.
This is why it works with a new DB file. You'll either need to modify the schema (which in SQLite involves creating a new table, copy data from the existing table, deleting existing table and then renaming the new table), or simply delete your old DB file and create a new one.

I had the same issue ... this is so stupid but it was because when I copied / pasted code from another table I forgot to change its name ......
Before
[Table("CopiedTable")]
After
[Table("MyNewTable")]

I had the same issue.
Doing Build/Clean sorted the problem for me.

I had the same problem in a Xamarin.Forms app on Android. This was caused by a not very obvious fact that the Model class can have fewer properties when it is build in the Release mode compared to the Debug mode. This is because of the linker. It removes the properties that are not directly referenced in the code but only in the Release version. The Debug version still contains all the properties. So when you run the Release version of the app and then its debug version, it crashes with this confusing error.
I have fixed it by adding [Preserve(AllMembers = true)] attribute to the class to make sure it is the same in both the Release and the Debug mode.

Related

_MigrationHistory not detected even though it exists

The following used to work. I am unsure what has changed.
var db = new MyDbContext()
var compatible = db.Database.CompatibleWithModel(true)
gives the following error
Model compatibility cannot be checked because the database does not
contain model metadata. Model compatibility can only be checked for
databases created using Code First or Code First Migrations.
I have been able to create and run the migrations using Package Manager and I can see the code in the Migrations folder.
I can see the migrations in the __MigrationHistory table.
I resolved the issue in a different database when the user did not have access to the table. However in this case the user does have access.
The table shows the product version is 6.4.4
I tried creating a new migration to see if there were any differences, but it was empty.
I looked at the configuration.cs in the migrations folder
internal sealed class Configuration : DbMigrationsConfiguration<MigrationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
}
Then I corrected the type
var db = new MigrationDbContext()
Then I changed the

Windows Phone dev - issues re-adding multi language resource files

I have a Windows Phone solution that was working fine. It had a couple of multi language resource files in a project that included all my shareable code.
However this project was incorrectly created as a Silverlight library, and I am now re-adding the classes etc back in as Windows Phone Class Library.
All good copying the files over .. except for the resource files. I ended up re-adding these manually and pasting the data in ... so I now have my AppResource.resx and AppResource.es-ES.resx okay.
But the code that uses them now gets an error that I cannot fathom.
Inconsistent accessibility: property type 'TimetableCommon.AppResource' is less accessible than property 'TimetableCommon.LocalisedStrings.Localisedresources'
The code is
namespace TimetableCommon
{
public class LocalisedStrings
{
public LocalisedStrings()
{
}
private static TimetableCommon.AppResource localisedresources = new TimetableCommon.AppResource();
public TimetableCommon.AppResource Localisedresources { get { return localisedresources; } }
}
}
Really lost with this... Only difference from the working version seems to me that the Spanish Resource file that I have recreated does not have the designer class underneath it. Not sure why.. and I don't think that's the problem here?
Any help appreciated.
Thanks
Ok... pretty dumb on my part.
In the resource files there is an access modifier combo box at the top that I had forgotten to alter.
I think I may have had the same problem first time around.

Can't load model using ContentTypeReader

I'm writing a game where I want to use ContentTypeReader. While loading my model like this:
terrain = Content.Load<Model>("Text/terrain");
I get following error:
Error loading "Text\terrain". Cannot find ContentTypeReader
AdventureGame.World.HeightMapInfoReader,AdventureGame,Version=1.0.0.0,Culture=neutral.
I've read that this kind of error can be caused by space's in assembly name so i've already removed them all but exception still occurs.
This is my content class:
[ContentTypeWriter]
public class HeightMapInfoWriter : ContentTypeWriter<HeightmapInfo>
{
protected override void Write(ContentWriter output, HeightmapInfo value)
{
output.Write(value.getTerrainScale);
output.Write(value.getHeight.GetLength(0));
output.Write(value.getHeight.GetLength(1));
foreach (float height in value.getHeight)
{
output.Write(height);
}
}
public override string GetRuntimeType(TargetPlatform targetPlatform)
{
return
"AdventureGame.World.Heightmap,AdventureGame,Version=1.0.0.0,Culture=neutral";
}
public override string GetRuntimeReader(TargetPlatform targetPlatform)
{
return
"AdventureGame.World.HeightMapInfoReader,AdventureGame,Version=1.0.0.0,Culture=neutral";
}
}
Does anyone meed that kind of error before?
I have been encountering the same problem for a week, and finally decided to do a quick check on the whole "assembly" part.
I found a fix!
Essentially, when you go into AssemblyInfo.cs, you will see all the properties(ie Title, Description, etc.)
The Title, sadly made by XNA, is NOT what your runtime reader refers to. Its actually getting the initial name of the project, which it uses to track back to your application (exe) file in your project. Try either re-making your project from scratch, making sure to keep your namespace the same as your project and never change it , or give a go at re-naming your exe file, found in the debug/obj folder in your project(i believe). hope I helped!
-Will

Getting CS1061 error on compile even though the property exists

I have come across the most curious problem ever as .Net dev. I am compiling a library which has a newly added property DeviceID in the class of UserInfo. The library internally uses the type and it's new property just fine, but when I try and reference it from another library, the compiler kicks back a compiler error stating
'library.UserInfo' does not contain a definition for 'DeviceID' and no extension
method 'DeviceID' accepting a first argument of type 'library.UserInfo' could
be found
Even though my class definition looks like:
public class UserInfo
{
public static UserInfo Current
{
get
{
if (UserInfoPrincipal.Current != null)
{
return UserInfoPrincipal.Current.UserData;
}
else
{
return null;
}
}
}
public string UserID { get; set; }
public string DeviceID { get; set; }
public string MikeLiUserID { get; set; }
public string TransactionServer { get; set; }
public string ApplicationKey { get; set; }
public string IpAddress { get; set; }
}
The offending code reads as such:
internal LogDetail BuildLogDetail(LogType entryType, string message)
{
return new LogDetail
{
ActingUserID = UserInfo.Current.UserID,
ActingDeviceID = UserInfo.Current.DeviceID,
ApplicationKey = UserInfo.Current.ApplicationKey,
IpAddress = UserInfo.Current.IpAddress,
EntryType = entryType,
OwnerID = UserInfo.Current.UserID,
LogData = message
};
}
I'd like to note that all of the other members of the UserInfo class go through the compiler correctly and it is just the DeviceID, which was added today, is causing the issue. I've tried Clean All, I've tried refreshing everything from TFS, manually deleting the obj and bin directories of both projects... nothing yet has worked.
UPDATE: This code, which is part of the library, works correctly:
public class UserInfoPrincipal : IPrincipal
{
public static UserInfoPrincipal Current
{
get
{
if (Thread.CurrentPrincipal is UserInfoPrincipal)
return (UserInfoPrincipal)Thread.CurrentPrincipal;
else
return null;
}
}
...
internal UserInfo UserData
{
get { return _userInfo; }
}
public string DeviceID
{
get { return _userInfo.DeviceID; }
}
...
}
So my hail mary pass was to remove the project reference and then add it again. Then it compiled. Have no clue why that worked, but figured I'd post it here for other who might run into the same problem.
Is the other library using a project reference or a binary reference? If its a binary reference, are you sure its using the latest build?
Check the reference path of the project that's generating the error; make sure you're either referencing the library project (if it's part of your solution) or the most recent build of the library (if it's not.)
I've gotten stuck in a few situations like this before. Here's what worked for me:
Are those two samples of code in separate projects? If so, I would say to try rebuilding the first project (containing the UserInfo class), then take out the line that fails the compilation out and try rebuilding the second project. Then do a rebuild all. Then add the offending line back in and do a rebuild all.
May not work for you, but worth a shot. I know that situation is frustrating.
for me -- try to recreate the line that shows an issue. Write the name of the object period (.) and wait for VS to show you the list of available properi
I encountered a very similar problem.
In my case I have a piece of code that I only need to run a couple times a year. When I attempted to use it there was an error accessing a Member. Nothing should have changed since the last time I used the code. Intellisense was detecting the member when using the '.' in Visual Studio. I restarted Visual Studio and the computer but the problem stayed.
In the end to fix my problem, I created a new file, copied the code from the original to the new file, and that was it. No code modifications. I used Ctrl-C, Ctrl-V so the content wasn't corrected by a manual touch. This isn't the first time copy and paste has fixed a bug so it's worth keeping the idea in the tool chest. Sometimes a mysterious problem demands an equally mysterious solution.
In my case, it was a problem with the web application's project properties. To fix it, I did the following:
Right-click the project > click Properties.
On the Build tab, change the Output path value for all configurations to: bin\
Previously, my output path had been bin\Debug or bin\Release depending on which configuration I was looking at. I don't know why this screwed with my markup page's ability to see methods in my codebehind, but it did. Once I changed this, the error disappeared.
This was in VS2012 w/ update 2.
My solution: I was create another name method what set property. My problem was on VS2015 + Silverlight 5

How to solve the following MappingException

I'm getting the following exception:
The number of members in the
conceptual type 'MyModel.Customer'
does not match with the number of
members on the object side type
'MyNamespace.Customer'. Make sure the
number of members are the same.
In the following code:
public CusomserService
{
// ...
public IEnumerable<Customer> GetCustomers()
{
return new Repository<Customer>().All();
}
}
public class Repository<T>() where T : EntityObject
{
// ...
public IQueryable<T> All()
{
return _context.CreateObjectSet<T>().AsQueryable<T>(); /* HERE THE EXCEPTION IS THROWN */
}
}
The generics repository was working fine until I made some changes in my EF Model. I'm letting EF create the database (through Generate database from Model option).
Where do I start?
EDIT: I've solved it.
The problem had nothing to do with EF or my model. I had renamed the data layer project (and it's assembly name) from original_name.dll to new_name.dll. I had updated the service layer project reference to the data layer project, but the the old assembly (original_name.dll) was still in the bin directory. Deleting the old assembly from the service layer's bin directory and rebuilding the solution solved the problem.
It seems that Classes 'MyModel.Customer' does not match with each other 'MyNamespace.Customer'.
Try right clicking on the edmx file and selecting Run Custom Tool
or right click on edmx in solution explorer and open with xml and verify your recent changes.

Categories

Resources