none
Disable Guid generation for one entity. EF Code First RRS feed

  • Question

  • Hello.

    I'm usinf EF Code First with and Azure Mobile Service and EF Code First. My entities all inherit from Microsoft.Azure.Mobile.Server.EntityData, which provides fields like Id, CreatedAt, UpdatedAt, etc, for my entities. By default, Id gets set with a new Guid, which is perfectly fine.

    Now, I have one entity that I would manually like to set the Id for (i.e., I don't want EF to set the Id as a new Guid for me). Is that possible? Maybe define an attribute or something when creating the class?

    Thanks.


    :. HUGONNE .: Please mark as answer if the post helps. Coding tips - http://hugonne.blogspot.com/

    Sunday, July 17, 2016 1:50 PM

Answers

  • Hi Hugonne,

    >>Now, I have one entity that I would manually like to set the Id for (i.e., I don't want EF to set the Id as a new Guid for me). Is that possible? Maybe define an attribute or something when creating the class?

    Based on your description, By default, Id gets set with a new Guid. it seems that you set a identity attribute on your id field (like below).  If it is the case. we could not set the value of guid property by manually. because it will be generated via database. we could not change it.

    public class EFBase
        {
            [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            public Guid Id { get; set; }
            public DateTime CreatedAt { get; set; }
        }
        public class Test : EFBase
        {
            public string name { get; set; }
        }

    In addition, if you want to set the value of guid by manually, I would suggest that you could create a model class does not

    inherit from Microsoft.Azure.Mobile.Server.EntityData. like this:

    public class ManualClass
        {
           public Guid Id { get; set; }
           public DateTime CreatedAt { get; set; }
           public string name { get; set; }
        }

    Best regards,

    Cole Wu


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Monday, July 18, 2016 3:22 AM
    Moderator