Either set a permanent value explicitly, or ensure that the database is configured to generate values for this property.'
Error Message
System.InvalidOperationException: 'The property 'DatabasePortfolio.EntityId' has a temporary value while attempting to change the entity's state to 'Deleted'. Either set a permanent value explicitly, or ensure that the database is configured to generate values for this property.'
This is just a memo.
There is no ID column that's why EFcore would delete row of temporary ID(0th).
when not exist IDNull(0th), Error message is shown .
Model(EF) deletes row from same ID , but View has only information on screen, so No ID column means not knowing ID then send ID(0th)
VM must row from View even if not exist ID, but Model(EF) cannot delete no exist row, that's why Error is shown.
Environment
VS 2026 / WPF / CommunityToolkit.Mvvm / EF Core
Struct:
View:DataGrid
Model:Entity(Table defintion)
Repository actually DB manipulate
Context connects DB and EFcore
Resolve
Just Insert this line on DataGrid setting. Add ID column.
<DataGridTextColumn Header="EntityID" Binding="{Binding EntityId}" />
Thoughts
ちゃんとメモして偉いとおもった。
Either set a permanent value explicitly, or ensure that the database is configured to generate values for this property.'
エラーメッセージ
System.InvalidOperationException: 'The property 'DatabasePortfolio.EntityId' has a temporary value while attempting to change the entity's state to 'Deleted'. Either set a permanent value explicitly, or ensure that the database is configured to generate values for this property.'
取り急ぎメモ程度に。
DataGridの列にID欄がないために、消したい行の持つIDとは別の、仮のID番号0番を削除しようとしている。
Deleteをする際に存在しないIDNull(番号0)を削除しようとして、エラーメッセージを出している。
Model(EF)はIDを探して一致する行を削除する。Viewは画面上の情報しか持っておらず、ID欄がないとIDを知らないことになるので、ID番号0を行情報と渡す。
VMは渡された番号と情報をModel(EF)に渡すしかないので、その行を渡す。
渡された行を消そうとするが存在しないモノは消せないとエラーになる。
開発環境と構成
環境:VS 2026 / WPF / CommunityToolkit.Mvvm / EF Core
構成:
View:DataGrid
Model:Entity(Table定義)
Repository 実際のDB操作
Context EF CoreのDB接続
解決法
XamlのDataGrid設定箇所に、IDの列を追加するだけ
<DataGridTextColumn Header="EntityID" Binding="{Binding EntityId}" />
感想
ちゃんとメモして偉いとおもった。
EF CoreでUPDATEのエラー処理をしたのにDataGridがもとに戻らない
開発環境と構成
環境:VS 2026 / WPF / CommunityToolkit.Mvvm / EF Core
構成:
View:DataGrid
VM:CRUD操作の仲介
Model:Entity(Table定義)
Repository 実際のDB操作
Context EF CoreのDB接続
問題
バリデーションエラー後の「表示」が戻らない
DataGridで不正な値を入力した際、エラーメッセージを出して「DBの元の値」に戻したい。
しかし、コード上でDBから値を読み直しても、DataGridの表示が古いエラー内容のまま残ってしまう。
試行錯誤
① 単純なREAD(全読み)
最初は `Read()` でリスト全体を読み直そうとしたが、DataGridが変わらない。
調べたりAIに聞いてみると、EF CoreはDBに変更がないとメモリ内のキャッシュから値を返すため、ただ読み直すだけでは「書き換えてしまったキャッシュの値」を再び読み込むだけだと判明。
② Reload()メソッドの発見
特定の1件(Entity")を強制的にDBと同期させる Reload()があるらしい。
Contextクラスに以下のメソッドを実装して呼び出した。
public void ReloadEntity(EntityType entity)
{
var entry = _context.Entry(entity);
entry.Reload();
}
ブレークポイントで確認すると、Collectionの中身は正しくDBの値に戻ったが、DataGridの表示は変わらない(でもTextBox側は戻る)。ヘッダーをクリックしてソートをすると表示が戻るという不思議な状態。
AIに相談するとデータは戻っているが、その変更がDataGridに通知されていないという事になった。
原因
通知(PropertyChange)の欠如
原因は、ModelのTableクラスがただの「自動プロパティ(get; set;)」のみで、通知機能を持たないクラスだったこと。
解決策
Tableクラスに ObservableObject を継承させ、プロパティを通知可能な形式に書き換え。
public class TableName : ObservableObject
{
}
これだけで、`Reload()` された瞬間にModel自身が「値が変わったよ!」と叫び、DataGridが即座に反応して表示が戻るようになった。
まとめ・流れ
- エラーになるような文字列を更新するデータに記入
- UPDATEボタンを押す
- Entityにエラーな値が入っているのでVMでエラーになる
- エラーメッセージが出る
- DBの最新情報を取得しメモリに記入、ここでEntityの値が変更(もとに戻る)される Reload()
- ObservableObjectを継承させたのでTableの行自身が値の変更通知を発信できる。
- 3と5で値が変わっているので、変更が発信されBindingしていたDataGridに通知が届き、DataGridが元のDBの状態に戻る
ちなみに
今回のケースでの[ObservableProperty] とObservableObjectで混乱しているので自分のために書くと。
DataGridは各列を1つのEntityとして捉え、各メンバーが変更されれば正しく描画されるのだが、VM側で[ObservableProperty] をつけたプロパティに直接元の値を代入して失敗したのは、この属性自体がインスタンスのメンバーのデータ変更ではなく、インスタンス自体が別の物に変わらないと変更通知が出ないから。だから各メンバーが変更されたら通知が発生するようにObservableObjectをTableに書くとTableのEntity"が自ら発信できるようになり、Gridが察知して正しく描画(DBと同期)された。
VM側で[ObservableProperty] をつけたプロパティはViewの入力フォームとVMをつなぐだけなので、DataGridにはUPDATEのとき変更の通知を送れなかった。VMのバインディングは TextBox.Text="{Binding InputEntity.PropertyName}" で、InputEntityプロパティ全体の変更(PropertyChanged("InputEntity"))を監視する。一方、DataGridのバインディングは ItemsSource="{Binding EntityList}" で、EntityListコレクション内の各エンティティインスタンスの個別プロパティ(EntityList[i].PropertyName)を監視する。
VM側で InputEntity = 新しいエンティティインスタンス をしても PropertyChanged("InputEntity") が発火するのは入力フォーム(TextBox)のみで、EntityListコレクションの中身には一切影響しないため、DataGridは更新されない。DataGridが更新されるには EntityList[i].PropertyName の PropertyChanged("PropertyName") 通知が必要になる。*ただし、本来はプロパティも SetProperty を使う形式に書き換える必要があるが、今回はReloadとUIの更新タイミングが重なり同期されたらしい。
感想
またAiを頼ってしまった。どうしよう。あとコレの英語版どんなかんじでかこう。うーん、しんどい。
XLS0507 View cannot find VM...
Intro
When I was coding MVVM app with wpf, VS2022 had told me this message on View Xaml,
:名前 "PortfolioVM" は名前空間 "clr-namespace:Portfolio.ViewModel" に存在しません。
"XLS0507: Type 'PortfolioVM' is not public or does not contain a public parameterless constructor or type converter, so it cannot be used as an object element."
Today , I have fixed this "XLS0507: " error.
Caution: This article is translated my Japanese page in this blog by me. You found lack of infomation or false something, please comment.
Cause
Once You set VM in<Window.DataContext>, Xaml searches no parameter VM's Constructor. Therefore, Xaml cannot find our Constructor that has papameters. Therefore Xaml shows us the message.
Solving
We are going to do Constructor Chaining.
We add this code in VM.cs
public PortfolioVM() : this(new PortfolioRepository()){}
more generally like thispublic NameofConstructor() : this(new ArgumentofConstructor()){}
By Stage
- Xaml only calls no parameter Constructor from <Window.DataContext>. This is cause of error
- However, VM's Constructor has parameter.
- We rewrite public PortfolioVM() as VS said , but our logic is broken with no parameter.
- Onece attached :this(new PortfolioRepository()) on no parameter Constructor, Compiler exects same name Constructor in VM.cs . This is Constructor Chaining.
- Thanks to Constructor Chaining, Compiler
finds :this(new CompanyRepository())." There are 2 same Name Constructors, but yeah it has :this() . Execute this Constructor first. Let me see... the parameter is instance of PortfolioRepository() . OK Ill pass the instance to same name Constructor, and let her/him Construct."
- in this way, no parameter Constructor will be called first, and passed the instance to having parameter Constructor then they work you want.
Afterword
I did googling many times , also tried ask to gpt and Gemini. These bunch of information makes me conffusing , thats why I wrote this article.
However, if Im in same situation in the future, I must not solve without AI's answer.
Eventually, I rely on Google and AI.
I could be a developer , Stop this way. its tough.
XLS0507 ViewがVMを見つけられないです
導入
WPFでMVVMのソフトを開発していたところBindingのためのコードをXamlで書いたあと、VMのクラスに次のようなエラーメッセージが出てきた。
:名前 "PortfolioVM" は名前空間 "clr-namespace:Portfolio.ViewModel" に存在しません。
XLS0507: 型 'PortfolioVM' はパブリックでないか、パラメーターなしのパブリック コンストラクターまたは型コンバーターを定義していないため、オブジェクト要素として使用できません。
今回はこのエラーを直してみた。
注意:この記事は日本語で下書きされたものを英語に書き換えたものです。文中で足りない情報や間違いがあればお手数ですが、コメントをお書きください。
原因
<Window.DataContext>にVMを設定すると、ViewのXamlは引数なしのVMを見つけてインスタンス化する。そのためビルドをした時点で、コンストラクタが引数を持っているとXaml(View)がコンストラクタを見つけられず、導入にあるエラーを吐いてしまう。
解決法
コンストラクタチェイニングを行う。
public PortfolioVM() : this(new PortfolioRepository()){}
をVMのクラス内にもう一つのコンストラクタとして追加する。汎用的ににするなら、
public NameofConstructor() : this(new ArgumentofConstructor()){}
だろう。
段落的に書くと
- <Window.DataContext>からは引数がないコンストラクタしか呼び出せない。これがエラーの原因
- しかし、VMのコンストラクタは引数がついている
- 言われた通りpublic PortfolioVM() : に書き換える。これにより引数なしコンストラクタという条件はクリアしたが、Repositoryを引数にできていないのでロジックが崩れてしまう。
- そこで、引数なしのコンストラクタに:this(new PortfolioRepository())をつけると同じCSの中の同名コンストラクタを実行する。:this()のカッコにはすでに設定したコンストラクタと同じ型の引数を記入する。これがコンストラクタチェイニング
- コンストラクタチェイニングによりコンパイラが
:this(new CompanyRepository())を見て「同じ名前だけど:this()が付いてるからまず先にこの部分を実行しなきゃ!。なになに引数にはCompanyRepository()のインスタンスをつかうのか。なら実体化して同じ名前のコンストラクタに渡そう!」
- このように判断して引数なしのコンストラクタを呼び出し、インスタンスをもとのロジックの書かれたコンストラクタに渡し、想定していたコンストラクタの動きを可能にする。
あとがき
色々調べたりして混乱したのとAIの情報を信じられなかったのでまとめてみた。
ただ、同じような状況に将来的になったとき何もみずにそして、AIに頼らずにクリアできるかは難しいだろう。
結局はAIやGoogleに頼りっぱなしである。
この癖を直さないことには開発者になれないだろう。辛い。
Could not save pictures into db with Maui and SQlite episode2
Episode 1 here
Causing2
Reason for ListView showing Items of picture
ListView must have a List to show at MainViewModel(Binding Context) not only binding ItemSource at Xaml.
Solution
Add the code at MainViewModel then, bind ItemSource.
For your information, [ObserverProperty] can generate automatically to Capital G "GazouByte" at Xaml ItemSource from field gazouByte at MainV MainViewModel
-
namespace WorkReview.ViewModels;
public partial class MainViewModel : ObservableObject
{
[ObservableProperty]
private string? statusMessage;[ObservableProperty]
private List<GazouByte>? gazouBytes; //here, List for MainPage[ObservableProperty]
private ImageSource? userPreview; //MainPageのプレビュー用
private string? gazouName; //ファイル名private byte[]? gazouBinary; //画像のバイナリデータ
private string? gazouExtension; //拡張子情報
public MainViewModel()
{ }[RelayCommand]
private void OnGetAllGazou() //画像リストの取得ボタン
{
GazouBytes = App.GazouByteRepo.GetAllGazouBytes();
StatusMessage = "got all file list"; StatusMessage = "got all file list";}
[RelayCommand]
private void OnFileSave()
{
if (gazouName == null) return;var gazouByte = new GazouByte
{
GazouName = gazouName!,
GazouBinary = gazouBinary!, //!はNull出ないことを宣言GazouExtension = gazouExtension!,
};App.GazouByteRepo.AddNewGazouByte(gazouByte);
StatusMessage = "file saved";
}
[RelayCommand]
private async Task OnFileSelect() //非同期でTaskとして結果を返す{
try
{
var result = await FilePicker.PickAsync();
if (result == null) return;
var fileName = result.FileName;if (fileName.EndsWith("jpg", StringComparison.OrdinalIgnoreCase) ||
fileName.EndsWith("png", StringComparison.OrdinalIgnoreCase))
{
using (var stream = await result.OpenReadAsync())
using (var memoryStream = new MemoryStream())
{
await stream.CopyToAsync(memoryStream);
gazouName = fileName;
gazouBinary = memoryStream.ToArray();
gazouExtension = result.ContentType;
var previewStream = new MemoryStream(memoryStream.ToArray());UserPreview = ImageSource.FromStream(() => previewStream);
}
}
else
{
StatusMessage = "Unsupported file type.";
}
}
catch (Exception ex)
{
StatusMessage = $"Error selecting file: {ex.Message}";
}
}
}
Afterword
As you can see from my past questions, I've been a bit of a pain with my inquiries. I'll try to be more considerate in the future.
I've realized I still have a lot to learn about MVVM and XAML.
But I was really impressed by how easily the people who answered my questions were able to solve problems I'd been stuck on for a week. I hope to be able to do that someday too.
I learned a lot just by asking questions, so thanks for that.
Could not save pictures into db with Maui and SQlite Episode1
Outline
I am creating file manager software with Maui and SQlite, so I reworked this page project
.NET MAUI アプリで SQLite を使用してローカル データを格納する - Training | Microsoft Learn
and save pictures into the db.
However, I cannot save pictures into the db also Listview does not show list.
Then, I ask a question in Teratail and StackOverflow.
Honestly, you can understand the error easily in these page than this blog . I wrote this page for my memorization
Problem Overview
What you are trying to do: I am trying to save image binary data into a SQLite database named gazouByte.db3 when the "Save" button is pressed after selecting an image file using a file picker. Additionally, I want to display the list of saved images, including their "Id," "File Name," and "Extension," in a CollectionView on the MainPage when the "Get All GazouList" button is pressed. What issue you are facing: The image binary data is not being saved to the gazouByte.db3 database. When clicking the "Get All GazouList" button, only "got all file list" is displayed, and the "Id," "File Name," and "Extension" are not shown. Note that the table gazouByte has been confirmed to be created using "DB Browser for SQLite."
-
Expected Behavior
When starting debugging, a table named gazouByte should be created in the app data. After selecting an image using the file picker, the selected image should be previewed under "Select File." When clicking the "Save File" button, the image data should be saved into the gazouByte.db3 database. Clicking the "Get All GazouList" button should display the "Id," "File Name," and "Extension" of the saved images in the CollectionView.
-
What I Have Tried
Verified that exception handling in GazouByteRepositry.AddNewGazouByte method is correctly implemented. Confirmed that the table gazouByte is created using "DB Browser for SQLite." Noticed that a System.NullReferenceException occurs when pressing the "Save File" button again without selecting a new image.
-
Error Messages and Logs
No error messages are displayed, but the image data is not saved.
-
Environment
Windows 11 Home 23H2 Visual Studio Community 2022 Preview 17.11.0 Preview 4.0 Microsoft.Maui.Controls 8.0.80 Microsoft .NET SDK 8.0.107 (x64) SQlitePCLRaw.bundle_green 2.1.9 sqlite-net-pcl 1.9.172 CommunityToolkit.Mvvm 8.2.2

db at DBbrowser
The question pages
Causing
Reason for not saving into db
-
The project had created db dupulicately that's why picture was not saved
-
MainviewModel recreated another db even db had already created at MauiProgram.cs, so pictures were not saved correct path.
-
namespace WorkReview
{
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
});
string dbPath = FileAccessHelper.GetLocalFilePath("gazouByte.db3");
builder.Services.AddSingleton< GazouByteRepositry> (s => ActivatorUtilities.CreateInstance< GazouByteRepositry> (s, dbPath));//Creating db as instance at App folder.↑ here
return builder.Build();
}
}
}
-
-
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommunityToolkit;
using CommunityToolkit.Mvvm.ComponentModel;
using WorkReview.Models;namespace WorkReview.ViewModels
{
public partial class MainViewModel : ObservableObject
{
private GazouByteRepositry _gazouByteRepositry;public MainViewModel()
{
_gazouByteRepositry = new GazouByteRepositry("gazouByte.db3");//↑ Create duplicately db at here
}[ObservableProperty]
public string gazouName;[ObservableProperty]
public string gazouPath;
[ObservableProperty]
public byte gazouBinary;
[ObservableProperty]
public string gazouExtension;
public void SaveGazouToDataBase()//MainPageから渡された画像データをRepositryへ送る。
{
var gazouByte = new GazouByte
{
GazouName = gazouName,
GazouBinary = gazouBinary,
GazouExtension = gazouExtension};
_gazouByteRepositry.AddNewGazouByte(GazouName, GazouBinary, GazouExtension);
}}
}
Solutions
I deleted the line and insert picture data directly into dbPath throw App.GazouByteRepo."MethodName" .
-
namespace WorkReview.ViewModels;
public partial class MainViewModel : ObservableObject
{
[ObservableProperty]
private string? statusMessage;[ObservableProperty]
private List<GazouByte>? gazouBytes; //MainPageのListView用のリスト。ListViewにはC#側にリストを作る必要がある。[ObservableProperty]
private ImageSource? userPreview; //MainPageのプレビュー用
private string? gazouName; //ファイル名private byte? gazouBinary; //画像のバイナリデータ
private string? gazouExtension; //拡張子情報
public MainViewModel()
{ }[RelayCommand]
private void OnGetAllGazou() //画像リストの取得ボタン
{
GazouBytes = App.GazouByteRepo.GetAllGazouBytes();
StatusMessage = "got all file list"; StatusMessage = "got all file list";}
[RelayCommand]
private void OnFileSave()
{
if (gazouName == null) return;var gazouByte = new GazouByte
{
GazouName = gazouName!,
GazouBinary = gazouBinary!, //!はNull出ないことを宣言GazouExtension = gazouExtension!,
};App.GazouByteRepo.AddNewGazouByte(gazouByte);//←forexample here
StatusMessage = "file saved";
}
[RelayCommand]
private async Task OnFileSelect() //非同期でTaskとして結果を返す{
try
{
var result = await FilePicker.PickAsync();
if (result == null) return;
var fileName = result.FileName;if (fileName.EndsWith("jpg", StringComparison.OrdinalIgnoreCase) ||
fileName.EndsWith("png", StringComparison.OrdinalIgnoreCase))
{
using (var stream = await result.OpenReadAsync())
using (var memoryStream = new MemoryStream())
{
await stream.CopyToAsync(memoryStream);
gazouName = fileName;
gazouBinary = memoryStream.ToArray();
gazouExtension = result.ContentType;
var previewStream = new MemoryStream(memoryStream.ToArray());UserPreview = ImageSource.FromStream(() => previewStream);
}
}
else
{
StatusMessage = "Unsupported file type.";
}
}
catch (Exception ex)
{
StatusMessage = $"Error selecting file: {ex.Message}";
}
}
}
-
-
Next Episode
*1:In Youtube and .Net . you can watch live streaming video