Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all articles
Browse latest Browse all 1698

Need my EF core to see already existing primary key in my SQL server table and work with it.

$
0
0

I have a SQL server DB table namely "RSBFileDetails", which has a primary key column "[File_Reference_Id]" auto generated int type. When I run my code to enter values in my DB using EF, I get an error: "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.'"

My code to enter data is: 

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);
                }
            }

 Highlighted code creates error message. 

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);
        }        
    }

How can I get my code to insert values into my database. Please help me with this 


Viewing all articles
Browse latest Browse all 1698

Trending Articles