programing

엔티티 프레임워크를 사용한ID 생성 및 자동 증분 방법

easyjava 2023. 3. 15. 20:02
반응형

엔티티 프레임워크를 사용한ID 생성 및 자동 증분 방법

투고 전체를 수정.

Fiddler를 통해 다음 JSON POST 요청을 게시하려고 합니다.

{Username:"Bob", FirstName:"Foo", LastName:"Bar", Password:"123", Headline:"Tuna"}

단, 이 에러는 표시됩니다.

Message "Cannot insert the value NULL into column 'Id', table 'xxx_f8dc97e46f8b49c2b825439607e89b59.dbo.User'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated." string

요청과 함께 랜덤 ID를 수동으로 보내도 괜찮습니다.다음과 같은 경우:

{Id:"1", Username:"Bob", FirstName:"Foo", LastName:"Bar", Password:"123", Headline:"Tuna"}

엔티티 프레임워크는 ID를 생성 및 자동으로 증가시키지 않는 이유는 무엇입니까?저의 POCO 클래스는 다음과 같습니다.

public class User
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public string Id { get; set; }
    public string Username { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Password { get; set; }
    public string Headline { get; set; }
    public virtual ICollection<Connection> Connections { get; set; }
    public virtual ICollection<Address> Addresses { get; set; }
    public virtual ICollection<Phonenumber> Phonenumbers { get; set; }
    public virtual ICollection<Email> Emails { get; set; }
    public virtual ICollection<Position> Positions { get; set; }
}

public class Connection
{
    public string ConnectionId { get; set; }
    public int UserId { get; set; }
    public virtual User User { get; set; }
}

public class Phonenumber
{
    public string Id { get; set; }
    public string Number { get; set; }
    public int Cycle { get; set; }
    public int UserId { get; set; }
    public User User { get; set; }
}

컨트롤러 방식은 다음과 같습니다.디버깅 모드에서 Fiddler를 통해 요청을 전송하면 다음 위치에서 중단됩니다.db.SaveChanges();위의 에러를 나타냅니다.

    // POST api/xxx/create
    [ActionName("create")]
    public HttpResponseMessage PostUser(User user)
    {
        if (ModelState.IsValid)
        {
            db.Users.Add(user);
            db.SaveChanges();

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, user);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = user.Id }));
            return response;
        }
        else
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        }
    }

뭐가 잘못됐나요?

솔루션

대신 문자열 ID를 int로 변경하고 데이터 주석을 제거하십시오.Id의 이름을 UserId로 변경(계속 규칙을 따르고 있음)하여 필요에 따라 다른 POCO에서 변경에 맞추어 변경.

이것은 추측입니다:)

아이디가 문자열이라서 그런가?int로 변경하면 어떻게 되나요?

내 말은:

 public int Id { get; set; }

테이블 디자인이 안 좋으시네요.문자열을 자동으로 늘릴 수 없습니다. 이 방법은 의미가 없습니다.기본적으로 다음 두 가지 옵션이 있습니다.

1) ID의 종류를 변경한다.int끈 대신
2) 권장하지 않음!!!- 자동 증가를 직접 처리합니다.먼저 데이터베이스에서 최신 값을 가져와 정수로 해석한 후 증분하여 엔티티에 다시 문자열로 부가해야 합니다.매우 나쁜 생각

첫 번째 옵션에서는 이 표를 참조하는 모든 표를 변경해야 하지만 그럴 가치가 있습니다.

언급URL : https://stackoverflow.com/questions/16079217/how-to-generate-and-auto-increment-id-with-entity-framework

반응형