wont save to database with guid as id- fluent-nhiberate

不羁岁月 提交于 2019-12-24 11:56:23

问题


i got problems with saving when i use Guid as identifier. can anybody se what i am missing here? i create my own guid so i dont want it to be generated by database.

NOTE: i have tried the guid.combo in mapping to without any success.

public class Order
{
    public virtual Guid Id { get; set; }
    public virtual ICollection<OrderItem> OrderItems { get; set; }
    public virtual User User { get; set; }
    public virtual DateTime? CreateDate { get; set; }
    public virtual DateTime? ShippedDate { get; set; }
    public virtual string OrderStatus { get; set; }

    public Order()
    {
        OrderItems = new Collection<OrderItem>();
    }

    public virtual void AddOrderItems(OrderItem orderItem)
    {
        orderItem.Order = this;
        OrderItems.Add(orderItem);
    }
}

OrderMap:

public OrderMap()
    {
        Id(x => x.Id).ColumnName("Id").GeneratedBy.Guid();

        Map(x => x.CreateDate);
        Map(x => x.ShippedDate);
        Map(x => x.OrderStatus);

        References(x => x.User);
        HasMany(x => x.OrderItems).Cascade.All().Inverse().LazyLoad();
    } 

回答1:


Id(x => x.Id).ColumnName("Id").GeneratedBy.Assigned()

Also .WithUnsavedValue(Guid.Empty) might be needed but I'm not sure. You'll probably need to tell NHibernate to use Save or Update (not SaveOrUpdate) each time, anyway. Not a big expert here... but you need to use .Assigned() for sure.




回答2:


you dont have to add GeneratedBy.Guid() it will work just fine also try using GeneratedBy.GuidComb(); it is recomended when using guids




回答3:


You can generate the guid before inserting the entity in the database. The benefit of that is that entities are the same before and after persitence in the database. It makes it easier to ignore the database in the code.

public class Order
{
   public Order()
   {
      Id = GuidGenerator.GenerateGuid();
   }

   public Guid Id { get; private set; }
}

public class Mapping
{
    Id(x => x.Id).GeneratedBy.Assigned().Access.AsCamelCaseField();
}

GuidGenerator.GenerateGuid() returns a guid generated by the guid comb algorithm or something like Guid.NewGuid()



来源:https://stackoverflow.com/questions/1481602/wont-save-to-database-with-guid-as-id-fluent-nhiberate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!