Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fk does not allow duplicate data in SQL Server (ASPNETZero)

I am using AspNet zero framework code first approach, i have two entities , parent questionOption and child entity userAnswer with Fk QuestionOptionId, UserAnswer does not allow duplicate QuestionOptionId even i dont create any index aur unique constrant on questionOptionId (i have mentioned picture). It doesnot give any exception or any error query execute successfully but does not create new duplicate/new record

what i have tried so far

  • if i input data manually with insert query SqlServe allows me to insert duplicate questionOptionId buy ASPNet zero does not add/insert any duplicate QuestionOptionId,
  • QuestionOptionId is not null field just for checking i made it nullable and tried to save duplicate record i creates new record but update previous record questionOptionId with null

here is my insertLink Query

 public async Task RCreateOrEdit(CreateOrEditUserAnswerDto input)
    {
var userAnswer = ObjectMapper.Map<UserAnswer>(input);
            if (AbpSession.TenantId != null)
            {
                userAnswer.TenantId = (int)AbpSession.TenantId;
            }

            await _userAnswerRepository.InsertAsync(userAnswer);
            await CurrentUnitOfWork.SaveChangesAsync();
            input.Id = userAnswer.Id;
}

this is what SQL SERVER created

enter image description here

ChildModel

 public class UserAnswer : FullAuditedEntity<long>, IMustHaveTenant
{
    public int TenantId { get; set; }


    public virtual long UserId { get; set; }

    public virtual long QuestionId { get; set; }

    public string UserComment { get; set; }

    public virtual long SessionId { get; set; }

    [ForeignKey("SessionId")]
    public Session SessionFk { get; set; }

    public virtual long QuestionOptionId { get; set; }
    public QuestionOption QuestionOptionFk { get; set; }

}

Desired Result: I want UserAnswer entity will allow me to add duplicate QuestionOptionFk

like image 787
Faraz Shaikh Avatar asked Jun 28 '26 23:06

Faraz Shaikh


1 Answers

public class UserAnswer : FullAuditedEntity<long>, IMustHaveTenant
{
    public int TenantId { get; set; }


    public virtual long UserId { get; set; }

    public virtual long QuestionId { get; set; }

    public string UserComment { get; set; }

    public virtual long SessionId { get; set; }

    [ForeignKey("SessionId")]
    public Session SessionFk { get; set; }

    public virtual long QuestionOptionId { get; set; }
    public ICollection<QuestionOption> QuestionOptionFk { get; set; }

}

Define relation using array of class instead of class according to Conventions of one to many relationship

like image 146
Khalil Avatar answered Jul 01 '26 14:07

Khalil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!