User-1660589204 posted
I have to check and save details of file(s) from a folder into a SQL server database. I am trying to do it but have some runtime error. Below is the code:
public async void PostValuesIntoDB()
{
DirectoryInfo info = new DirectoryInfo(path);
FileInfo[] fileInfos = info.GetFiles("*.trm");
if (fileInfos != null || fileInfos.Length>0)
{
foreach (FileInfo fileInfo in fileInfos)
{
RsbfileDetail detail = new RsbfileDetail();
detail.Filename = fileInfo.Name;
detail.FileUrl = fileInfo.FullName;
detail.FileType = fileInfo.Extension;
detail.CreatedDate = fileInfo.CreationTime;
await _rSBRepository.Add(detail);
}
}
Below is the error that occurs at the highlighted line:
System.InvalidOperationException: 'Unable to track an instance of type 'RsbfileDetail' because it does not have a primary key. Only entity types with primary keys may be tracked.'
I have checked in my Database, which has a [RSBFileDetails] table with "[File_Reference_Id] [int] IDENTITY(1,1) NOT NULL" column as primary key.
My repository code is and fields are autogenerated:
public interface IRSBRepository : IRepository<RsbfileDetail>
{
Task<RsbfileDetail> UploadFiles(string filename);
public void GetNewFileFromFolderToDB();
Task<string> Add(RsbfileDetail rsbfileDetail);
}
RSBRepository.cs
public class RSBRepository : Repository<RsbfileDetail>, IRSBRepository
{
private readonly rsbsrdbContext _dbContext;
public RSBRepository(rsbsrdbContext dbContext) : base(dbContext)
{
_dbContext = dbContext;
}
Task<RsbfileDetail> IRSBRepository.UploadFiles(string filename)
{
throw new NotImplementedException();
}
public async Task<string> Add(RsbfileDetail rsbfileDetail)
{
string dbresult = string.Empty;
_dbContext.Add(rsbfileDetail);
var response= await _dbContext.SaveChangesAsync();
dbresult = response.ToString();
return dbresult;
}
public void GetNewFileFromFolderToDB()
{
List<RsbfileDetail> result1 = new List<RsbfileDetail>();
result1 = _dbContext.RsbfileDetails.Where(j => (j.Filename == "sample.txt")).ToList();
Console.WriteLine(result1);
}
}
Can anyone help me solve this issue please