code first database : SqlException: Violation of PRIMARY KEY constraint 'PK_dbo.PrivatKasses'. - sql

I have a model like this:
class PrivatKasse
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ID { get; set; }
public decimal Betrag { get; set; }
public int BenutzerID { get; set; }
}
and a function that checks if the table is empty. if yes functions adds new rows. The function:
public static void DatabaseChecker()
{
using (var _db = new DataContext())
{
if (!_db.KasseGemeinsam.Any())
{
_db.KasseGemeinsam.Add(new Models.Data.KasseGemeinsamModel() { Jahr = DateTime.Now.Year.ToString(), Monat = MonatenVertauchen.ZahlZuMonaten(Convert.ToInt32(DateTime.Now.Month)), Haushalt = 0, Hygine = 0, Mobel = 0, Nahrung = 0, Schreibware = 0, Sonstiges = 0 });
_db.SaveChanges();
}
if (!_db.KassePrivat.Any())
{
_db.KassePrivat.Add(new Models.Data.KassePrivatModel() { Jahr = DateTime.Now.Year.ToString(), Monat = MonatenVertauchen.ZahlZuMonaten(Convert.ToInt32(DateTime.Now.Month)), UserID = UserIdentity.UserID, Fahrkosten = 0, Hygine = 0, Mobel = 0, Nahrung = 0, Schreibware = 0, Sonstiges = 0 });
_db.SaveChanges();
}
if (!_db.GemeinsamKasse.Any())
{
_db.GemeinsamKasse.Add(new Models.Data.GemeinsamKasse() { Betrag = 0 });
_db.SaveChanges();
}
if (!_db.PrivatKasse.Any())
{
List<int> userIDs = new List<int>();
foreach (var item in _db.UsersTbl)
{
userIDs.Add(item.ID);
}
using (var _db2 = new DataContext())
{
foreach (var item in userIDs)
{
_db2.PrivatKasse.Add(new Models.Data.PrivatKasse() { BenutzerID = item, Betrag = 0 });
}
_db2.SaveChanges();
}
}
}
But I get an SqlExeption :
System.Data.Entity.Infrastructure.DbUpdateException: "An error occurred while updating the entries. See the inner exception for details."
UpdateException: An error occurred while updating the entries. See the
inner exception for details.
SqlException: Violation of PRIMARY KEY constraint
'PK_dbo.PrivatKasses'. Cannot insert duplicate key in object
'dbo.PrivatKasses'. The duplicate key value is (0).
The statement has been terminated.
How can i fix this problem?

I believe the issue is because you are not providing the id (and the default in a int is 0) since you declare
[DatabaseGenerated(DatabaseGeneratedOption.None)]
which means that the db will not create the id, I recommend to use Identity instead
[DatabaseGenerated(DatabaseGeneratedOption.Identity )]
then you should be able to use
_db2.PrivatKasse.Add(new Models.Data.PrivatKasse() { BenutzerID = item, Betrag = 0 })
otherwise provide the id
_db2.PrivatKasse.Add(new Models.Data.PrivatKasse() {ID= customID, BenutzerID = item, Betrag = 0 })

Related

PATCH in web API for Many to Many relationships using EF

I'm trying to remove a tag from a list of tags using a PATCH request. But while saving changes to the db context I get the following error:.
This the the PATCH code.
[HttpPatch("{id:int}/{field}", Name = "UpdateNote")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult UpdateNote(int id, string field, JsonPatchDocument<CreateNoteDTO> patchNoteDTO)
{
if (id == 0 || patchNoteDTO == null)
return BadRequest();
var note = _db.Notes.AsNoTracking().FirstOrDefault(u => u.ID == id);
if (note == null)
return NotFound();
CreateNoteDTO createNoteDTO = _mapper.Map<CreateNoteDTO>(note);
if (field.Equals("tags"))
{
var tags = _db.Tags.Where(u => u.Notes.Any(x => x.ID == note.ID)).AsNoTracking().ToList();
List<TagDTO> tagDTOs = new List<TagDTO>();
if (tags.Count > 0)
{
foreach (var tag in tags)
{
TagDTO tagDTO = _mapper.Map<TagDTO>(tag);
tagDTOs.Add(tagDTO);
}
}
createNoteDTO.Tags = tagDTOs;
}
patchNoteDTO.ApplyTo(createNoteDTO, ModelState);
if (!ModelState.IsValid)
return BadRequest(ModelState);
Note updateNote = _mapper.Map<Note>(createNoteDTO);
updateNote.ID = id;
updateNote.ChangedDate = DateTime.Now;
_db.Update(updateNote);
if (!field.ToLower().Equals("category"))
_db.Entry(updateNote).Property(u => u.FKCategory).IsModified = false;
_db.Entry(updateNote).Property(u => u.CreatedDate).IsModified = false;
_db.SaveChanges();
return NoContent();
}
My ApplicationDBContext looks like this:
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<Note> Notes { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Tag> Tags { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//Write Fluent API configurations here
modelBuilder.Entity<Note>()
.HasOne(e => e.Category)
.WithMany(e => e.Notes)
.HasForeignKey(e => e.FKCategory)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Note>()
.HasMany(n => n.Tags)
.WithMany(t => t.Notes)
.UsingEntity(j => j
.ToTable("NoteTag")
.HasData
(
new { NotesID = 1, TagsTagID = 1 },
new { NotesID = 2, TagsTagID = 2 }
));
modelBuilder.Entity<Category>().HasData
(
new Category
{
CategoryID = 1,
CategoryName = "testCategory1",
CreatedDate = DateTime.Now
},
new Category
{
CategoryID = 2,
CategoryName = "testCategory2",
CreatedDate = DateTime.Now
}
);
modelBuilder.Entity<Tag>().HasData
(
new Tag
{
TagID = 1,
TagName = "testTag1",
CreatedDate = DateTime.Now
},
new Tag
{
TagID = 2,
TagName = "testTag2",
CreatedDate = DateTime.Now
}
);
modelBuilder.Entity<Note>().HasData
(
new Note
{
ID = 1,
Title = "testTitle1",
Description = "testDescription1",
FKCategory = 1,
Deleted = false,
CreatedDate = DateTime.Now,
ChangedDate = DateTime.Now,
},
new Note
{
ID = 2,
Title = "testTitle2",
Description = "testDescription2",
FKCategory = 2,
Deleted = false,
CreatedDate = DateTime.Now,
ChangedDate = DateTime.Now,
}
);
}
}
Any suggestions?
Thanks in advance.
Initially I tried without the following if condition:
CreateNoteDTO createNoteDTO = _mapper.Map<CreateNoteDTO>(note);
if (field.Equals("tags"))
{
var tags = _db.Tags.Where(u => u.Notes.Any(x => x.ID == note.ID)).AsNoTracking().ToList();
List<TagDTO> tagDTOs = new List<TagDTO>();
if (tags.Count > 0)
{
foreach (var tag in tags)
{
TagDTO tagDTO = _mapper.Map<TagDTO>(tag);
tagDTOs.Add(tagDTO);
}
}
createNoteDTO.Tags = tagDTOs;
}
But I got a different error:
I wanted to remove a tag form the following object using a PATCH request:
Note Object

null userId, Unhandled Exception: Null check operator used on a null value

I have an issue with userId in Habits table. it is a foreign key from id in Users Table. but I keep getting the error "Unhandled Exception: Null check operator used on a null value " from AddHabitDialogController class.
obviously userId should never be null. where is the issue? how can I solve it?
if more code is needed you can check : https://github.com/sarasoltan/habit_tracker
Users Table:
class UsersTable {
static const String tableName = 'Users';
static const String id = 'id';
static const String email = 'email';
static const String createQuery = '''
CREATE TABLE IF NOT EXISTS $tableName (
$id integer primary key autoincrement,
$email text not null unique);''';
#override
String toString() => 'Person, ID: $id, email: $email';
#override
bool operator ==(covariant Users other) => id == other.id;
#override
int get hashCode => id.hashCode;
}
Habits table:
class HabitsTable {
static const String tableName = 'Habits';
static const String id = 'id';
static const String userId = 'userId';
static const String text = 'text';
static const String emoji = 'emoji';
static const String period = 'period';
static const String startPeriod = 'startPeriod';
static const String createQuery = '''
CREATE TABLE IF NOT EXISTS $tableName (
$id integer primary key autoincrement,
$userId integer not null,
$text text not null,
$emoji text not null,
$period text not null,
$startPeriod integer,
FOREIGN Key($userId) REFERENCES ${UsersTable.tableName}(${UsersTable.id}));''';
User model class:
class Users {
late final int id;
late String email;
Users({
required this.id,
required this.email,
});
Users.fromDb(Map<String, dynamic> map) {
id = map[UsersTable.id];
email = map[UsersTable.email];
}
}
Habit model class:
class Habit {
late final int id;
late final int userId;
late String text;
late String emoji;
late final List<int> period;
late final DateTime? startPeriod;
Habit(
{
//required this.id,
required this.userId,
required this.text,
required this.emoji,
required this.period,
this.startPeriod});
Habit.fromDb(Map<String, dynamic> map) {
id = map[HabitsTable.id] as int;
userId = map[HabitsTable.userId] as int;
text = map[HabitsTable.text] as String;
emoji = map[HabitsTable.emoji];
period = (jsonDecode(map[HabitsTable.period]) as List<dynamic>)
.map((e) => e as int)
.toList();
if (map[HabitsTable.startPeriod] != null) {
startPeriod =
DateTime.fromMillisecondsSinceEpoch(map[HabitsTable.startPeriod]);
} else {
startPeriod = null;
}
}
Map<String, dynamic> toDb() {
Users? owner;
return {
//HabitsTable.id: id,
HabitsTable.userId: owner!.id,
HabitsTable.text: text,
HabitsTable.emoji: emoji,
HabitsTable.period: jsonEncode(period),
HabitsTable.startPeriod: startPeriod?.millisecondsSinceEpoch
};
}
AddHabitDialogController(error):
class AddHabitDialogController {
Users? owner;
//final user = FirebaseAuth.instance.currentUser;
//String get owneruserId => AuthService.firebase().currentUser!.id;
final List<bool> period = [true, true, true, true, true, true, true];
int? id;
int? userId;
String? emoji;
String? text;
StartPeriod startPeriod = StartPeriod.none;
final StreamController<bool> _addBtnEnabledCtrl = StreamController();
Stream<bool> get addBtnEnabled => _addBtnEnabledCtrl.stream;
final StreamController<StartPeriod> _selectedStartPeriodCtrl =
StreamController();
Stream<StartPeriod> get selectedStartPeriod =>
_selectedStartPeriodCtrl.stream;
final StreamController<bool> _loadingCtrl = StreamController();
Stream<bool> get loading => _loadingCtrl.stream;
void changePeriodValue(int index, bool newValue) {
period[index] = newValue;
_updateAddBtnEnabledState();
}
void changeTextValue(String newValue) {
text = newValue;
_updateAddBtnEnabledState();
}
void changeEmojiValue(String newEmoji) {
emoji = newEmoji;
_updateAddBtnEnabledState();
}
void changeStartPeriod(StartPeriod newValue) {
startPeriod = newValue;
_selectedStartPeriodCtrl.add(startPeriod);
}
Future<void> addHabit(BuildContext context) async {
_loadingCtrl.add(true);
final dataService = GetIt.I.get<DataService>();
final List<int> forPeriod = [];
for (int i = 0; i < period.length; i++) {
if (period[i]) {
forPeriod.add(i + 1);
}
}
final habit = Habit(
//id: id!,
userId: owner!.id, //error from here
emoji: emoji!,
text: text!,
period: forPeriod,
startPeriod: _calculateStartPeriodDateTime());
await dataService.addHabit(habit);
_loadingCtrl.add(false);
Navigator.of(context).pop();
}
void _updateAddBtnEnabledState() {
_addBtnEnabledCtrl.add((text?.isNotEmpty ?? false) &&
(emoji?.isNotEmpty ?? false) &&
period.where((e) => e).isNotEmpty);
}
DateTime? _calculateStartPeriodDateTime() {
final now = DateTime.now();
switch (startPeriod) {
case StartPeriod.today:
return DateTime(now.year, now.month, now.day);
case StartPeriod.thisMonth:
return DateTime(now.year, now.month);
case StartPeriod.thisYear:
return DateTime(now.year);
case StartPeriod.none:
default:
return null;
}
}
void dispose() {
_addBtnEnabledCtrl.close();
_loadingCtrl.close();
_selectedStartPeriodCtrl.close();
}
}
enum StartPeriod { none, today, thisMonth, thisYear }
Because the local variable of AddHabitDialogController owner can't be referenced before it is declared
class AddHabitDialogController {
Users? owner; // -> you did not assign this owner?

Read Data attributes or Custom Attributes in SQL server from string

I want in SQL prepared dynamic query based on the shortcode.
For Eg.
DECLARE #ShortCode VARCHAR(MAX)
SET #ShortCode = '[User data="Name" data="MobileNumber"]';
User = table name
Name = User table field
MobileNumber = User table field
Query output be like
SELECT [Name],[MobileNumber] FROM [dbo].[User]
SET #ShortCode = '[Country data="Name" ID="1"]';
Country = table name
Name = Country table field
ID = User table field
Query output be like
SELECT [Name] FROM [dbo].[Country] WHERE [ID] = 1
How to extract all data attributes values and how to get User in the []
This functionality is done in C#
Here My c# code
// Model class
public class ShortCodeResult
{
public Guid? ID { get; set; }
public string TableName { get; set; }
public bool IsValidShortCode { get; set; }
public string Message { get; set; }
public Dictionary<string,object> KeyValue { get; set; }
public ShortCodeResult() {
KeyValue = new Dictionary<string, object>();
ID = Guid.NewGuid();
}
}
//Regex Filter
public class RegexFilter
{
private string oPattern = #"(\w+)=[\""]([a-zA-Z0-9_.:\""]+)";
public ShortCodeResult GetShortCodeValues(string Code)
{
var oShortCodeModel = new ShortCodeResult();
var oRegex = new Regex(oPattern, RegexOptions.IgnoreCase);
var oTableNameRegex = Regex.Match(Code, #"\b[A-Za-z]+\b", RegexOptions.Singleline).Value;
var lstMatchCollection = oRegex.Matches(Code).Cast<Match>().Where(x=>x.Value.StartsWith("data")).ToList();
if (lstMatchCollection != null && lstMatchCollection.Count > 0)
{
for (int i = 0; i < lstMatchCollection.Count; i++)
{
var oSelected = new Regex("[^=]+$").Match(Convert.ToString(lstMatchCollection[i]));
if (oSelected != null)
{
oShortCodeModel.KeyValue.Add(i.ToString(), oSelected.Value.Trim('"'));
}
}
}
oShortCodeModel.TableName = oTableNameRegex;
return oShortCodeModel;
}
}
//HtmlHelper Extension
public static MvcHtmlString RenderShortCode(this HtmlHelper htmlHelper, string IdOrExprssion)
{
#region Get short code data
var oShortCode = ShortCodeHelper.GetShortCode(IdOrExprssion);
#endregion
var oMvcHtmlString = new MvcHtmlString(IdOrExprssion);
var oRegexFilter = new RegexFilter();
var shortCodeModel = oRegexFilter.GetShortCodeValues(oShortCode.Expression);
var ostringBuilder = new StringBuilder();
if (!string.IsNullOrEmpty(shortCodeModel.TableName))
{
ostringBuilder.AppendLine("SELECT ");
ostringBuilder.AppendLine((shortCodeModel.KeyValue.Count > 0 ? string.Join(",", shortCodeModel.KeyValue.Select(x => x.Value)) : "*"));
ostringBuilder.AppendLine(" FROM ");
ostringBuilder.AppendLine(oShortCode.TableName);
ostringBuilder.AppendLine(" WITH(NOLOCK) ");
if (oShortCode.FilterCode.Count() > 0)
{
ostringBuilder.AppendLine("WHERE ");
foreach (var filterCode in oShortCode.FilterCode)
{
ostringBuilder.AppendLine(filterCode.FilterColumnName);
ostringBuilder.AppendLine(filterCode.Operator);
ostringBuilder.AppendLine(filterCode.FilterColumnValue);
}
}
}
var oDyanamicData = DBHelper.GetDataTable(ostringBuilder.ToString(), System.Data.CommandType.Text, new List<SqlParameter>());
if (oDyanamicData != null)
{
if (oShortCode.IsHtmlRender)
{
for (int i = 0; i < oDyanamicData.Rows.Count; i++)
{
for (int j = 0; j < oDyanamicData.Columns.Count; j++)
{
string key = Convert.ToString(oDyanamicData.Columns[j]);
string value = Convert.ToString(oDyanamicData.Rows[i].ItemArray[j]);
if (oShortCode.DisplayCode.Count > 0)
{
var displayCode = oShortCode.DisplayCode.FirstOrDefault(x => x.DisplayColumnName == key);
if (displayCode != null && !string.IsNullOrEmpty(displayCode?.ReplaceKey))
{
oShortCode.DefinedHtml = oShortCode.DefinedHtml.Replace(displayCode.ReplaceKey, value);
}
}
}
}
return new MvcHtmlString(oShortCode.DefinedHtml);
}
else
{
string key = string.Empty, value = string.Empty;
#region For Json
List<JObject> dataList = new List<JObject>();
for (int i = 0; i < oDyanamicData.Rows.Count; i++)
{
JObject eachRowObj = new JObject();
for (int j = 0; j < oDyanamicData.Columns.Count; j++)
{
key = Convert.ToString(oDyanamicData.Columns[j]);
value = Convert.ToString(oDyanamicData.Rows[i].ItemArray[j]);
eachRowObj.Add(key, value);
}
dataList.Add(eachRowObj);
}
return new MvcHtmlString(Newtonsoft.Json.JsonConvert.SerializeObject(dataList));
#endregion
}
}
return oMvcHtmlString;
}
Can anyone help me solved above in SQL server or prepared query in store procedure

datediff with case statement in select query linq

select case statement in linq query.
Here is the query on sql:
select case when DATEDIFF(day,convert(varchar,Min([Order].CreatedOnUtc),101),convert(varchar,Max([Order].CreatedOnUtc),101)) = 0 then
Sum([Order].OrderSubtotal)
else
case when (DATEDIFF(day,convert(varchar,Min([Order].CreatedOnUtc),101),convert(varchar,Max([Order].CreatedOnUtc),101))/30) = 0 then Sum([Order].OrderSubtotal) else
Sum([Order].OrderSubtotal)/
(DATEDIFF(day,convert(varchar,Min([Order].CreatedOnUtc),101),convert(varchar,Max([Order].CreatedOnUtc),101))/30)
end
end as 'Account Value' from [order] where And Account.ID = #Act_ID
I am trying the code here:
var query = _orderRepository.Table;
query = query.Where(o => o.AccountId == accountId);
In query i am getting my value.
After query statement what should i write??
how do i write for case statement using linq???
#Manoj, may be the below code helps you. This sample C# project may solve the problem you have.
using System;
using System.Collections.Generic;
using System.Linq;
namespace DateDiffIssue
{
class Program
{
static void Main(string[] args)
{
// Preparing data
var data = new Order[] {
new Order { AccountID = 1, CreatedOnUtc = DateTime.Parse("1.01.2017 10:00"), OrderSubtotal = 100 },
new Order { AccountID = 1, CreatedOnUtc = DateTime.Parse("1.01.2017 12:00"), OrderSubtotal = 150 },
new Order { AccountID = 1, CreatedOnUtc = DateTime.Parse("1.01.2017 14:00"), OrderSubtotal = 150 }
};
// Selection
var selected = (from item in data
let accountData = data.Where(w => w.AccountID == 1)
let minDate = accountData.Min(m => m.CreatedOnUtc).Date
let maxDate = accountData.Where(w => w.AccountID == 1).Max(m => m.CreatedOnUtc).Date
let isSameDate = minDate == maxDate
let basedOn30Days = (maxDate - minDate).TotalDays / 30
let isInside30Days = (int)basedOn30Days == 0
let accountDataSum = accountData.Sum(s => s.OrderSubtotal)
select new
{
AccountValue = isSameDate ? accountDataSum :
isInside30Days ? accountDataSum :
accountDataSum / basedOn30Days
}).Distinct();
// Print each order
selected.ToList().ForEach(Console.WriteLine);
// Wait for key
Console.WriteLine("Please press key");
Console.ReadKey();
}
}
internal class Order
{
public int AccountID { get; set; }
public DateTime CreatedOnUtc { get; set; }
public int OrderSubtotal { get; set; }
}
}

Rhino Mock and Method Not Returning Correct Value

Does anyone know why UsernameExists wont return True. I must have my syntax messed up somewhere.
[TestMethod()]
public void GenerateUsername_AppendTwoCharacters_ReturnUsernameWithTwoAppendedCharacters()
{
var usersRepository = MockRepository.GenerateStub<IUsersRepository>();
var target = new StudentsService(null, null, usersRepository, null, null, null, null);
usersRepository.Expect(q => q.UsernameExists("", null)).Return(true);
var actual = target.GenerateUsername("test", "student", "280000");
Assert.AreEqual("A", actual);
}
public string GenerateUsername(string firstName, string lastName, string studentNumber)
{
var originalusername = new StudentUsernameGenerator(firstName, lastName, studentNumber).Generate(2, 2, 4);
var username = originalusername;
if (!string.IsNullOrWhiteSpace(username))
{
decimal maxCharacters = 26;
var counter = 0;
var overflow = 1;
while (_usersRepository.UsernameExists(username, null))
{
counter++;
if (counter > maxCharacters)
{
overflow++;
counter = 1;
}
username = GetCharacterPaddingForDuplicateUsername(counter, overflow, originalusername);
}
}
return username;
}
I had to add IgnoreArguments
usersRepository.Stub(q => q.UsernameExists("", null)).IgnoreArguments().Return(true);