Explict Value can't be inserted in Table when IDENTITY_INSERT is OFF - entity-framework

I get an error when I try to insert a value in my Table.
_dltype is an object of type BRIDownloadType.
using (var db = new BRIDatabase())
{
foreach (var client in db.BRIClients)
{
var todo = new BRIToDo
{
BRIClient = client,
BRIDownloadType = _dltype,
};
db.BRIToDos.Add(todo);
}
db.SaveChanges();
}
Now I get the error:
An Explict Value can't be inserted in the Idendity Column in the BRIDownloadTypes-Table when IDENTITY_INSERT is OFF.
My 2 Tables are
BRIDownloadType
public class BRIDownloadType
{
[Key]
public int DlTypeId { get; set; }
[Required]
[StringLength(15)]
public string DlType { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public virtual ICollection<BRIToDo> BRIToDo { get; set; }
}
BRITodo
public class BRIToDo
{
[Key]
public int ToDoId { get; set; }
[ForeignKey("BRIClient")]
public int ClientId { get; set; }
[ForeignKey("BRITask")]
public int TaskId { get; set; }
public virtual BRIClient BRIClient { get; set; }
public virtual BRITask BRITask { get; set; }
[ForeignKey("BRIDownloadType")]
public int DlTypeId { get; set; }
public virtual BRIDownloadType BRIDownloadType { get; set; }**
}
The interesting thing is, if I do something with my _dltype object, I can use it.
The following code is working and I don't understand why, I'm inserting the exact same object.
using (var db = new BRIDatabase())
{
var dl = db.BRIDownloadTypes.FirstOrDefault(c => c.DlTypeId == _dltype.DlTypeId);
foreach (var client in db.BRIClients)
{
var todo = new BRIToDo
{
BRIClient = client,
BRIDownloadType = _dltype,
};
db.BRIToDos.Add(todo);
}
db.SaveChanges();
}
Can anybody explain to me, why the last approach is working and the first is throwing that error? I just added the line
var dl = db.BRIDownloadTypes.FirstOrDefault(c => c.DlTypeId == _dltype.DlTypeId)
But I'm still inserting the same object. If I insert the Id of the object instead of the object it is also working fine. I have no idea whats going on there.

Related

EF Core 6: Reading two tables using navigations doesn't load child table data

The role property of a relation record doesn't get read/initialized (i.e. the data from the included table doesn't get read). Why is that? The data is in the database.
public class IDM_Role
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public long role_id { get; set; } = -1;
[StringLength(80)]
public string role_name { get; set; } = string.Empty;
}
public class IDM_Relation
{
[Required]
[StringLength(80)]
public string account_id { get; set; } = string.Empty;
[Required]
[ForeignKey("IDM_Role")]
public long role_id { get; set; } = 0;
[ForeignKey("role_id")]
public virtual IDM_Role role { get; set; }
}
modelBuilder.Entity<IDM_Relation>()
.HasKey(e => new { e.role_id, e.account_id })
.HasName("PK_IDM_Relation");
[EnableQuery(PageSize = 15)]
public IQueryable<IDM_Relation> Get()
{
return _context.idm_relations.Include(e => e.role);
}
Removing "virtual" from the property IDM_Role role doesn't help.

Entity Framework always adds two records in the tables

I'm implementing an ASP.NET Core 3.1 app. I have implemented following code to insert record in SQL Server database via EF Core but each time I save data, it inserts two records in PersonRequester and Requester table. I appreciate if anyone suggests me how I can prevent reinserting records.
Requester ap = new Requester();
ap.Address = RequesterViewModel.Requestervm.Address;
ap.RequesterType = RequesterViewModel.Requestervm.RequesterType;
ap.Description = RequesterViewModel.Requestervm.Description;
ap.Name = RequesterViewModel.Requestervm.Name;
var pa = new PersonRequester()
{
BirthCertificateNo = RequesterViewModel.personRequestervm.BirthCertificateNo,
IssuePlace = RequesterViewModel.personRequestervm.IssuePlace,
NationalCode = RequesterViewModel.personRequestervm.NationalCode,
Requester = ap
};
using (var context = new DBContext())
{
context.PersonRequester.Attach(pa);
try
{
context.SaveChanges();
}
catch (Exception e)
{
throw e;
}
}
public partial class Requester
{
public Requester()
{
PersonRequester = new HashSet<PersonRequester>();
}
public int RequesterId { get; set; }
public int RequesterType { get; set; }
public string Address { get; set; }
public string Description { get; set; }
public string Name { get; set; }
public virtual EntityType RequesterTypeNavigation { get; set; }
public virtual ICollection<PersonRequester> PersonRequester { get; set; }
}
public partial class PersonRequester
{
public int RequesterId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public int RequesterType { get; set; }
public string NationalCode { get; set; }
public string BirthCertificateNo { get; set; }
public string IssuePlace { get; set; }
public virtual Requester Requester { get; set; }
public virtual EntityType RequesterTypeNavigation { get; set; }
}

Entity Framework mapping 2 one to many with existing DB and Model

I have been trying to update a project of my with Entity Framework. I have an existing database and model, which after some work matched. With some more work, I managed to get the application to successfully read the data from the database. But when saving new data, the nightmare started.
In my data structure, I have 2 one-to-many relations, one between player and team and one between match and team. I have been trying many configurations (with [Key], foreign key, inverse property attributes) but I either get an error
Trying to cast List to team
or
no column found Match_id no column found Player_id
This is my code:
public class Match
{
//[Key]
//[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string Id { get; set; }
//[Column("Date")]
public DateTime Date { get; set; }
public DateTime EndTime { get; set; }
[NotMapped]
public bool Remove { get; set; }
//[InverseProperty("Match")]
[ForeignKey("MatchId")]
public virtual ICollection<Team> Teams { get; set; }
public int WinningTeamId { get; set; }
public MatchType MatchType { get; set; }
public string Source { get; internal set; }
public Match()
{
WinningTeamId = -1;
this.Teams = new List<Team>();
this.EndTime = (DateTime)SqlDateTime.MinValue;
}
}
public class Team
{
public int TeamId { get; set; }
[NotMapped]
public int RatingChange { get; set; }
[Key()]
[Column("PlayerId", Order = 2)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public virtual Player Player { get; set; }
[Column(Order = 1)]
[Key()]
//[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string MatchId { get; set; }
[ForeignKey("MatchId")]
public virtual Match Match { get; set; }
[NotMapped]
public int Rating { get; set; }
public Team()
{
}
}
public class Player
{
public string name { get; set; }
public int PastatsId { get; set; }
public string UberId { get; set; }
//[ForeignKey("PlayerId")]
//[InverseProperty("Player")]
public virtual ICollection<Team> Teams { get; set; }
//[Key()]
public int Id { get; set; }
}
To save the new matches, I first save the players to prevent conflicts there:
public void Save(IEnumerable<Match> matches)
{
foreach (var match in matches)
{
foreach (var team in match.Teams)
{
var entry = Entry(team.Player);
if (entry.State == EntityState.Detached)
{
var localplayer = Players.Local.FirstOrDefault(x => x.UberId == team.Player.UberId);
if (localplayer == null)
{
this.Players.Add(team.Player);
team.Player = entry.Entity;
}
else
{
team.Player = localplayer;
}
}
else
{
Entry(team.Player).State = EntityState.Modified;
}
}
}
SaveChanges();
foreach (var match in matches)
{
if (Matches.Find(match.Id) != null)
{
continue;
}
if (Entry(match).State == EntityState.Detached)
{
this.Matches.Add(match);
}
}
SaveChanges();
}
How to do this mapping with an existing database and code?
Any insight will be gratefully appreciated.

LiteDB null reference on insert

I ran into this problem where in I get a null reference exception on insert.
I have two object Models UserInfo and UserConfig. On the first trial, UserConfig references a UserInfo instance
public class UserConfigObject : IUserConfig
{
BsonRef("userInfo")]
public IUserInfo UserInfo { get; set; }
public string AssignedJob { get; set; }
public string[] QueueItems { get; set; }
}
public class UserInfoObject : IUserInfo
{
[BsonId]
public int ID { get; set; }
public string Name { get; set; }
public string Username { get; set; }
public string IPAddress { get; set; }
}
And a method to insert the data into the database
public void AddUser(IUserConfig user)
{
var uconCollection = DatabaseInstance.GetCollection<IUserConfig>("userConfig");
var uinCollection = DatabaseInstance.GetCollection<IUserInfo>("userInfo");
uinCollection.Insert(user.UserInfo);
uconCollection.Insert(user);
}
This set up works fine but when I try to change the reference to UserInfo references UserConfig
public class UserInfoObject : IUserInfo
{
[BsonId]
public int ID { get; set; }
public string Name { get; set; }
public string Username { get; set; }
public string IPAddress { get; set; }
[BsonRef("userConfig")]
public IUserConfig UserConfig { get; set; }
}
public class UserConfigObject : IUserConfig
{
[BsonRef("userInfo")]
public IUserInfo UserInfo { get; set; }
[BsonId(true)]
public int ConfigID { get; set; }
public string AssignedJob { get; set; }
public string[] QueueItems { get; set; }
}
With a method call for
public void AddUser(IUserInfo user)
{
var uconCollection = DatabaseInstance.GetCollection<IUserConfig>("userConfig");
var uinCollection = DatabaseInstance.GetCollection<IUserInfo>("userInfo");
uconCollection.Insert(user.UserConfig);
uinCollection.Insert(user);
}
It no longer works, it throws an System.NullReferenceException: 'Object reference not set to an instance of an object.' on uinCollection.Insert(user);
Either v3 or v4, it doesn't work with the latter set up
Had the same problem but with collections. I've tried to save collection of invitations like so:
using var db = new LiteRepository(_connectionString);
var invitations = new List<Invitation>
{
// populate list
};
db.Insert(invitations);
The problem is that T parameter resolved as IEnumerable<Invitation> not just Invitation, so if you are inserting a collection, set type explicitly.
db.Insert<Invitation>(invitations);

NullReference error when adding a new model into a model property

I have the following entity framework code first models:
public class Member {
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string City { get; set; }
public String CardNumber { get; set; }
//Foreign Key
public virtual ICollection<Favorite> Favorites { get; set; }
[NotMapped]
public List<SelectListItem> FavoriteTypes { get; set; }
public Member() {
MembersDB db = new MembersDB();
FavoriteTypes = new List<SelectListItem>();
FavoriteTypes.AddRange(db.FavoriteTypes.ToList().Select(f => new SelectListItem { Text = f.Value, Value = f.ID.ToString() }));
}
}
public class FavoriteType {
public int ID { get; set; }
public string Value { get; set; }
}
public class Favorite {
public int ID { get; set; }
public String Value { get; set; }
//Foreign Keys
public virtual FavoriteType FavoriteType { get; set; }
public virtual Member Member { get; set; }
}
This creates a 1-M relationship for FavoriteTypes -> Favorites and 1-M relations for Member -> Favorites
Within my controller action, I retrieve most of the Member's info from Session saved at a couple pages back except for the favorites info which is gathered below. Then I gather the list of ID and input values to add to my new member as so:
[HttpPost]
public ActionResult AddFavs(List<int> ID, List<string> Value) {
MembersDB db = new MembersDB();
Member newMember = (Member)Session["member"];
if (ID != null && Value != null)
{
for (int i = 0; i < ID.Count(); i++)
{
int currentID = ID[i];
var test = new Favorite();
test.FavoriteType = db.FavoriteTypes.Where(f => f.ID == currentID).FirstOrDefault();
test.Value = Value[i];
newMember.Favorites.Add(test);
}
}
While running this code I get a NullReference error on this line newMember.Favorites.Add(test);
Not entirely sure why, any help would be appreciated.
EDIT: while troubleshooting in VS, the only null properties I can find are Favorites in newMember and Member in test
ICollection<Favorite> Favorites is null, so you can't add items to it. You should instantiate it in the constructor of your model:
public Member()
{
Favorites = new List<Favorite>();
// ...
}
Now it's an empty collection and you can add items to it.